When default constructor of base class has not been defined, then there is no need to refer base class constructor in derived class. But if any base class constructor has been defined with one or more arguments then it is mandatory for all derived classes to define constructors and supply arguments for their base classes.
Base class constructor executes first followed by derived class constructor. In multi-level inheritance the order of constructor call is depends upon the order of inheritance. In multiple inheritance the order of constructor call follows the order of base class specification in the header of derived class definition.
The header of derived class constructor has two parts. First part is the list of arguments to the constructor followed by a colon. And the second part is the constructor calls of base classes.
DerCns(dtype arg1, dtype arg2, dtype arg3, dtype arg4):base1Cns(arg1),base2Cns(arg2)
When virtual base class is participating in inheritance then its constructor will be invoked regardless of order of appearance in header of derived class definition
Eg: class A: public B, virtual public C { };
In the above case constructor of virtual base class C will be called before ordinary base class B and finally constructor of derived class A.
//Example C++ program to demonstrate order of constructor calls from derived class
#include<iostream>
using namespace std;
class alpha
{
int x;
public:
alpha(int i)
{
x=i;
cout<<“alpha is initialisedn”;
}
void showX(void)
{
cout<<“value of x is “<<x<<“n”;
}
};
class beta
{
float y;
public:
beta(float j)
{
y=j;
cout<<“beta is initialised n”;
}
void showY(void)
{
cout<<“value of Y is : “<<y<<“n”;
}
};
class gamma:public beta, public alpha
{
int m,n;
public:
gamma(int a, float b, int c, int d):alpha(a),beta(b) //alpha(a) and beta(b) are function calls
{
m=c;
n=d;
cout<<“gamma is initialised n”;
}
void showMN(void)
{
cout<<“value of m is “<<m<<endl
<<“value of n is: “<<n<<endl;
}
};
main()
{
gamma g(5,10.75,20,30);
cout<<endl;
g.showX();
g.showY();
g.showMN();
}