Constructors and Destructors in Inheritance in C++

Constructors & Destructors in Inheritance in C++

Constructors and Destructors In inheritance

It is very interesting for the curious learner to know whether constructors and destructors also inherited parent class to child class or not

When we are using the constructors and destructors in the inheritance, parent class  constructors and destructors are accessible to the child class hence when we create an object for the child class, constructors and destructors of both parent and child class get executed

 

Constructors and Destructors In inheritance

Let us look at below example to understand what happens –

Order of Calling For Constructors & Destructors in Inheritance in C++

C++ program to the sequence of execution of constructor and destructor inheritance

#include<iostream>
using namespace std;

class parent//parent class
{
public:
parent()//constructor
{
cout<<"Parent class Constructor\n";
}

~parent()//destructor
{
cout<<"Parent class Destructor\n";
}
};

class child : public parent//child class
{

public:
child() //constructor
{
cout<<"Child class Constructor\n";
}

~ child() //destructor
{
cout<<"Child class Destructor\n";
}
};

int main()
{

child c;//automatically executes both child and parent class //constructors and destructors because of inheritance

return 0;
}

O/P

Parent class Constructor 
Child class Constructor
Child class Destructor
Parent class Destructor

Inheritance in Parametrized Constructor/ Destructor

In the case of the default constructor, it is implicitly accessible from parent to the child class but parametrized constructors are not  accessible to the derived class automatically, for this reason, explicit call has to be made in the child class constructor for accessing the parameterized constructor of the parent class to the child class using the following syntax

<class_name>:: constructor(arguments)

Note: Whenever you are using the parameterized constructor in parent class it  is mandatory to define a default constructor explicitly

Example program

#include<iostream>
using namespace std;

class parent
{

int x;
public:
// parameterized constructor
parent(int i)
{
x = i;
cout << "Parent class Parameterized Constructor\n";
}
};

class child: public parent
{

int y;
public:

// parameterized constructor
child(int j) : parent(j) //Explicitly calling
{
y = j;
cout << "Child class Parameterized Constructor\n";
}
};

int main()
{
child c(10);

return 0;
}

O/P

Parent class Parameterized Constructor
Child class Parameterized Constructor

Constructor call in multiple inheritance constructors

class C: public A, public B;

Constructors are called upon the order in which they are inherited
First class A constructors are executed followed by class B constructors, then class C constructors