Inheritance construction & destruction order

A Child class derived from a Parent can be thought of as consisting of two parts: a Parent from which it inherits the Parent's members and its own Child part which has its own members.

 

The inherited Parent of a Child class is constructed before the Child.

 

Thus multiple inherited classes have the most senior class constructed before its child classes are constructed and so on down the chain of inheritance.

 

Similarly, a class's destructors destroy each part of a Child's derived classes, starting from the Child's own top level before destroying its inherited parts.

 

For example, a Child that is derived from a Parent that is derived from a Grand-Parent, will firstly have the Grand-Parent constructed, then the Parent before finally constructing the Child. Destruction starts with the Child, then the Parent and finally the Grand-Parent:

#include<iostream>
#include <string>
using namespace std ;

class First{
	public :
	First(){
		cout << "Constructing 1" << endl ;
	}
	~First(){
		cout << "Destroying 1" << endl << endl ;
	}
};

class Second : public First {
	public :
	Second(){
		cout << "Constructing 2" << endl ;
	}
	~Second(){
		cout << "Destroying 2" << endl ;
	}
};

class Third : public Second {
	public :
	Third(){
		cout << "Constructing 3" << endl << endl ;
	}
	~Third(){
		cout << "Destroying 3" << endl ;
	}
};

int main(){

	cout << "Instantiating one:" << endl ;
	First one ;

	cout << endl << "Instantiating two:" << endl ;
	Second two ;

	cout << endl << "Instantiating three" << endl ;
	Third three ;

	return 0 ;
}

Compile & Run:

Instantiating one:
Constructing 1 

 

Instantiating two:
Constructing 1
Constructing 2

 

Instantiating three
Constructing 1
Constructing 2
Constructing 3

 

Destroying 3
Destroying 2
Destroying 1

 

Destroying 2
Destroying 1

 

Destroying 1

Leave a Reply