Static function in abstract class

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

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);

};

      

+2


a source to share


4 answers


First of all, this function needs a return type. I guess it should be void

.

You implement it in your source file just like any other method:



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

      

There is nothing special about it being static or the class Item

being abstract. The only difference is that you don't have access to the pointer this

(and therefore the member variables) inside the method.

+4


a source


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



void Item::enableDebug(bool)
{    
}

      

+1


a source


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

0


a source


Most modern C ++ compilers can (now) handle a static method implementation inside a 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 some of them are outlined in previous answers.

0


a source







All Articles