A derived class constructor always calls the constructor for its base class first to initialize the derived class’s base-class members.
If the derived-class constructor is omitted, the derived class’s default constructor calls the base class’s default constructor.
As the classes may have several constructors defined, you need to specify explicitly the relationship between constructors:
Derived(int a, float b) : Base(a) { derivedB = b; }
class Base {
private:
int num;
public:
Base( int n = 0 ) : num(n) { cout<< "Base is called ..."; }
int getNum();
};
class Derived : public Base {
private:
float val;
public:
Derived(int n = 0, float v=0.0);
};
// definition of the constructor for Derived class
Derived :: Derived(int n, float v) : Base(n), val(v)
{
cout << "Derived is called" << endl;
}
Derived der1(3, 4.5); // will result in calling Base(n) then Derived(..)
This isn’t inheriting in the usual sense though, see page 628-629...
http://en.cppreference.com/w/cpp/language/using_declaration
From C++11, a derived class can reuse the constructors of a direct base.
We use ...
using Base::Base
... and then not explicitly define derived class constructors.