Derived Class Constructors:
In inheritance, a constructor of the derived class as well the constructor functions of the base class arc automatically executed when an object of the derived class is created.
The following example explains the concept of execution of constructor functions in single inheritance.
Program:
#include <iostream.h>
#include <conio.h>
calss BB
{
public:
BB (void)
{
cout << “Construction of Base Class” << endl;
}
};
class DD : public BB
{
public:
DD (void)
{
cout << “Construction of Derived Class” << endl;
}
};
Main ( )
{
DD abc;
getch ( );
Output of Program
Construction of Base Class
Construction of Derived Class
Constructors in Single Inheritance with Arguments:
In case of constructor functions with arguments, the syntax to define constructor of the derived class is different. To execute a constructor of the base class that has arguments through the derived class constructor, the derived class constructor is defined as:
- Write the name of the constructor function of the derived class with
parameters. - Place a colon immediately after this and then write the name of the constructor function of the base class with parameters.
The following example explains the concept of the constructor function with arguments in single inheritance.
class student
{
private:
char name [15];
char address [25];
public:
student (char nm [], char adr [] );
void show (void);
};
class marks : public student
{
private :
int sub1, sub2, sub3, total;
public:
marks (char nm [], char adr [], int a, int b, int c) : student (nm, adr);
void show-detail ( );
};
comment closed