views:

254

answers:

2

In the header, 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."

+8  A: 

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.

sth
If there is more then one ctor, make sure you set it in all of them.
pmr
@pmr: Abstract classes are often used as virtual base classes. For virtual base classes it's a bad idea to implement anything but a default constructor. But, yeah, if the class isn't used as a virtual base class, you're right.
sbi
So the answer would be that I should add : isActive(false) to the constructors of each class that inherits from AbstractClass?
VGambit
It is a virtual base class; should it have a default constructor? I don't think it would ever actually be used.
VGambit
I wouldn't say "often." In my career I've written dozens of abstract classes. I can count the number that turned into virtual base classes on one hand.
JohnMcG
What I think @sbi was trying to say is that if your class is a virtual base class it should only have one constructor, so @pmr's comment would not apply.
JohnMcG
@JohnMcG: Yes, I was trying to say that. Thanks for jumping in.
sbi
@VGambit: you add the constructor for AbstractClass and then isActive is set. Your derived class constructors will automatically call base class constructors, so the item will be properly initialized. AFAIK, you cannot put base class members into your initialization list. As an aside- I might make isActive a parameter to the ctor, e.g. AbstractClass(bool isActive=false) : isActive(isActive) { }
dash-tom-bang
@dash-tom-bang: I did a bit of research to better understand what you said, and learned something new about C++: base classes are required to have default constructors. I'll do what you said and put isActive in both the default constructor and its initialization list.
VGambit
@VGambit- all classes have constructors, but there's no requirement for a "default" constructor; if you don't define one then it won't be created for you and any time you create that (sub)object, you'll need to pass the parameters to it.
dash-tom-bang
A: 

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.

tpdi