Invocation of constructors and Destructors C++

Most of the time you are confused when you read in a program comment that constructor invoked or destructor invoked.

The sequence of invocation of constructors and Destructors in C++ is different in different situations. Let’s see them one by one.

How and in which sequence constructor and destructor invoked in C++

constructors Invoked and Destructors Invoked C++

Simple Class (no inheritance): Invocation of constructors and Destructors – [C++]

Let’s see the Simple Class invocation of constructors and Destructors in C++.

Output

First: T4Tutorials class constructor.

Second: T4Tutorials class destructor.

If we want to know the sequence of Invocation of constructors and destructors, then it is important to know that it depends on the type of inheritance being used.
Here, I am demonstrating the sequence in which constructors and destructors are called in single and multiple inheritence.

Constructor and destructor invocation (invoked)in single inheritance
In single inheritance, firstly, parent class constructors are called and then the chile class constructors are called.
Destructor and Destructor invocation (invoked)in single inheritance

In single inheritance, firstly, Child class destructors are called and then the parent class destructors are called.

Single inheritance: Invocation of constructors and Destructors – [C++]

Let’s see the invocation of constructors and Destructors in Single inheritance in C++.

Output

The output of the program will be;

The base class constructor called first

The derived class constructor called second.

The derived class destructor called first.

The base class destructor called second.

Multiple inheritence: Invocation of constructors and Destructors – [C++]

Let’s see the invocation of constructors and Destructors in Multiple inheritance in C++.

Output:

First: T4Tutorials_Parent1 class constructor.

Second: T4Tutorials_Parent2 class constructor.

Third: derived class constructor.

First: derived class destructor.

Second: T4Tutorials_Parent2 class destructor.

Third: T4Tutorials_Parent1 class destructor.

Multilevel inheritance: Invocation of constructors and Destructors – [C++]

Let’s see the invocation of constructors and Destructors in Multi Level inheritance in C++.

Output:

First: T4Tutorials_GrandFather class constructor.

Second: T4Tutorials_Father class constructor.

Third: T4Tutorials_Child class constructor.

First: T4Tutorials_Child class destructor.

Second: T4Tutorials_Father class destructor.

Third: T4Tutorials_GrandFather class destructor.

Video Lecture