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:
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.
Call base constructor in member initialize list
if you want to, actually Super() constructor is automatically called.
Don't forgot to make Super destructor virtual.
class Super {
public:
int x, y;
Super() : x(100),y(100) {}
virtual ~Super(){}
};
If deletion through a pointer to a Super should be allowed, then Super destructor must be public and virtual.
: Super()
… - Potatoswatter