C++: Constructors And Destructors 12

The sequence of execution of constructors and destructors

Whenever an object of a class is declared the constructor function of the class automatically gets called/invoked. We cannot invoke/call the constructor functions of the class using an object.

The destructor function gets executed in reverse order of the creation of the objects.

We may have a situation when a class contains objects of other classes as its data elements, then in such a case, the constructors of the member objects are invoked first, and then only, the constructors of the containing class is invoked.

Example:1
Give the output of the following program code?

#include<iostream>
using namespace std;
class A
{
public:
	A()
	{
	  cout<<"Constructor of class A"<<endl;
	}
	~A()
	{
	  cout<<"Destructor of class A"<<endl;
	}
};
class B
{
public:
	B()
	{
	  cout<<"Constructor of class B"<<endl;
	}
	~B()
	{
	  cout<<"Destructor of class B"<<endl;
	}
};
class C
{
public:
	C()
	{
	  cout<<"Constructor of class C"<<endl;
	}
	~C()
	{
	  cout<<"Destructor of class C"<<endl;
	}
};

int main()
{
	A a1;
  	B b1;
  	C c1;
 	return(0);
}

Output:

Constructor of class A
Constructor of class B
Constructor of class C
Destructor of class C
Destructor of class B
Destructor of class A