Order of constructor Invocation/ Sequence of execution of constructors
Whenever an object of a class is declared the constructor function of the class automatically gets called/invoked.
The destructor function gets executed in reverse order of the creation of the objects.
Example:1
#include<iostream> using namespace std; class A { public: A() { cout<<"Constructor of class A"<<endl; } }; class B { public: B() { cout<<"Constructor of class B"<<endl; } }; class C { public: C() { cout<<"Constructor 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
Note:
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 containing class is invoked.
Example:2
#include<iostream> using namespace std; class A { public: A() { cout<<"Constructor of class A"<<endl; } }; class B { public: B() { cout<<"Constructor of class B"<<endl; } }; class C { A a1,a2; B b1; public: C() { cout<<"Constructor of class C"<<endl; } }; int main() { C c1; return(0); }
/* Output */ Constructor of class A Constructor of class A Constructor of class B Constructor of class C