Use constructor's member initializer lists:
class Super {
public:
int x, y;
Super() : x(100), y(100) // initialize x and y to 100
{
// that was assignment, not initialization
// x = y = 100;
}
};
class Sub : public Super {
public:
float z;
Sub() : z(2.5) { }
};
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:
class Super {
public:
int x, y;
explicit Super(int i) : x(i), y(i) // initialize x and y to i
{ }
};
class Sub : public Super {
public:
float z;
Sub() : Super(100), z(2.5) { }
};
Furthermore, any constructor that can be called without arguments is a default constructor, too. So you can do this:
class Super {
public:
int x, y;
explicit Super(int i = 100) : x(i), y(i)
{ }
};
class Sub : public Super {
public:
float z;
Sub() : Super(42), z(2.5) { }
};
class AnotherSub : public {
public:
AnotherSub() { }
// this constructor could be even left out completely, the compiler generated
// one will do the right thing
};
And only call it explicitly when you don't want base members to be initialized with default value.
Hope that helps.