开发者

C++ How do I give a member variable in an abstract class a default value?

开发者 https://www.devze.com 2022-12-31 20:12 出处:网络
In the head开发者_JAVA技巧er, I\'m defining bool isActive. In classes derived from this one, I would like to make isActive false by default. I tried doing this by adding

In the head开发者_JAVA技巧er, I'm defining bool isActive. In classes derived from this one, I would like to make isActive false by default. I tried doing this by adding

AbstractClass::isActive = false; 

to the cpp file, but that causes the error "Expected constructor, destructor, or type conversion before '=' token."


Initialize it in the class' constructor:

class AbstractClass {
   bool isActive;

   AbstractClass() : isActive(false) {
   }

   // ...
};

That the class contains abstract methods doesn't stop it from having a constructor that is used to initialize its member variables.


AbstractClass::isActive = false;

refers to a (non-existent) static class member. If that existed, it would exist as a single shared instance for the entire class, and you would in fact initialize it as you did.

But you have an instance variable, which means that every instance of the class has its own copy. To initialize that, you'd do what sth say; initialize it in the class's ctor, either in the ctor body or better, as sth suggests, in the initializer list.

0

精彩评论

暂无评论...
验证码 换一张
取 消