tags:

views:

63

answers:

4

How to implement a static function in an abstract class?? Where do I implement this?

class Item{
public:
  //
  // Enable (or disable) debug descriptions. When enabled, the String produced
  // by descrip() includes the minimum width and maximum weight of the Item.
  // Initially, debugging is disabled.
  static enableDebug(bool);

};
A: 

Static functions cannot be virtual so you implement it in the context of the class itself. It doesn't matter if the class is abstract or not.

void Item::enableDebug(bool)
{    
}
Brian R. Bondy
+4  A: 

First of all, that function needs a return type. I'll assume it's supposed to be void.

You implement it in a source file, just as you would implement any other method:

void Item::enableDebug(bool toggle)
{
  // Do whatever
}

There's nothing special about it being static or the Item class being abstract. The only difference is that you do not have access to a this pointer (and consequently also not to member variables) within the method.

Tyler McHenry
A: 

Static methods can be implemented in any class. I just don't know if your method can be made static. Your comments suggest that the method will set some object data. In this case, your method cannot be static.

Juliano
A: 

Most modern C++ compilers can (now) handle having static method implementation inside the class declaration, as in:

class Item {
public:

  static void enableDebug(bool value) {
      static bool isOn = false;
      isOn = value;
      std::cout << "debug is " << (isOn ? "on" : "off") << std::endl;
  }

};

I'm not saying this is a good idea, but does flesh out the previous answers some.

Simeon Fitch