class Base
{
protected:
int a, b;
public:
Base() {}
Base(int aa, int bb) { a = aa; b = bb; }
};
1 2 3 4 5 6 7 8 9 10
class Derived : public Base
{
protected:
int c
public:
Derived() {}
Derived(int aa, int bb, int cc) { Base(aa, bb); c = cc; }
// OR
Derived(int aa, int bb, int cc) : Base(aa, bb), c(cc) {}
};
The two definition of the derived class constructor
1 2 3
(Derived(int aa, int bb, int cc) { Base(aa, bb); c = cc; }
and
Derived(int aa, int bb, int cc) : Base(aa, bb), c(cc) {}
The member variables are constructed before the body of the class constructor is evaluated.
This one uses initializer list:
1 2 3 4 5
Derived(int aa, int bb, int cc)
: Base(aa, bb), // these are constructor calls, initialization
c(cc)
{
}
The other can be written more explicitly:
1 2 3 4 5 6 7 8 9 10
Derived(int aa, int bb, int cc)
: Base(),
c()
{
Base(aa, bb); // error.
// This probably creates a temporary unnamed Base object,
// which is different from the Base-part of Derived
c = cc; // this is an assignment
}