When a class is declared, a constructor can be declared inside the class to initialize data members. When a base class contains a constructor with one or more arguments then it is mandatory for the derived class to have a constructor and pass arguments to the base class constructor. When both the derived and base classes contain constructors, the base constructor is executed first and then the constructor in the derived class is executed. The constructor of derived class receives the entire list of values as its arguments and passes them on to the base constructors in the order in which they are declared in the derived class.
General form to declare derived class constructor:
Derived-constructor (arglist1, arglist (D)):Base1(arglist1)
{
Body of derived class constructor
}
Derived constructor declaration contains two parts separated with colon (:). First part provides declaration of arguments that are passed to the derived constructor and second part lists the function calls to the base constructors.
Example:
#include<iostream.h>
#include<conio.h>
class base
{
int x;
public:
base(int a)
{
x=a;
cout<<"Constructor in base x="<<x;
}
};
class derived: public base
{
int y;
public:
derived(int a,int b):base(a)
{
y=b;
cout<<"Constructor in derived.y="<<y;
}
};
void main()
{
clrscr();
derived ob(2,3);
getch();
}
In the above example, base class constructor requires one argument and derived class constructor requires one argument. Derived class constructor accepts two values and passes one value to base class constructor.