aherlambang
aherlambang

Reputation: 14418

static function in an abstract class

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

};

Upvotes: 3

Views: 10144

Answers (4)

metasim
metasim

Reputation: 4960

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.

Upvotes: 1

Juliano
Juliano

Reputation: 811

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.

Upvotes: 0

Tyler McHenry
Tyler McHenry

Reputation: 76670

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.

Upvotes: 6

Brian R. Bondy
Brian R. Bondy

Reputation: 347256

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)
{    
}

Upvotes: 1

Related Questions