Possible Duplicate:
C++ superclass constructor calling rules
How do you delegate work to the superclass’ constructor? For instance
class Super {
public:
int x, y;
Super() {x = y = 100;}
};
class Sub : public Super {
public:
float z;
Sub() {z = 2.5;}
};
How do I get Sub::Sub() to call Super::Super() so that I don’t have to set x and y in both constructors?
Use constructor’s member initializer lists:
You don’t need to explicitly call base class’ default constructor, it’s automatically called before derived class’ constructor is ran.
If, on the other hand, you want base class to be constructed with parameters (if such constructor exists), then you need to call it:
Furthermore, any constructor that can be called without arguments is a default constructor, too. So you can do this:
And only call it explicitly when you don’t want base members to be initialized with default value.
Hope that helps.