C++: Inheritance |sequence of execution of constructors and destructors in inheritance

Hierarchical inheritance

Example:1

//Sequence of execution of constructors and destructors
//Multiple inheritance
#include<iostream>
using namespace std;
class A
{
public:
    A()
    {
      cout<<"Constructor function of class A"<<endl;
    }
    ~A()
    {
      cout<<"Destructor function of class A"<<endl;
    }
};
class B:public A
{
public:
    B()
    {
      cout<<"Constructor function of class B"<<endl;
    }
    ~B()
    {
      cout<<"Destructor function of class B"<<endl;
    }
};
class C:public A
{
public:
    C()
    {
      cout<<"Constructor function of class C"<<endl;
    }
    ~C()
    {
      cout<<"Destructor function of class C"<<endl;
    }
};
int main()
{
  B b1;
  C c1;
  return(0);
}


Output:

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

Example:2

//Sequence of execution of constructors and destructors
//Multiple inheritance
#include<iostream>
using namespace std;
class A
{
public:
    A()
    {
      cout<<"Constructor function of class A"<<endl;
    }
    ~A()
    {
      cout<<"Destructor function of class A"<<endl;
    }
};
class B:public A
{
public:
    B()
    {
      cout<<"Constructor function of class B"<<endl;
    }
    ~B()
    {
      cout<<"Destructor function of class B"<<endl;
    }
};
class C:public A
{
public:
    C()
    {
      cout<<"Constructor function of class C"<<endl;
    }
    ~C()
    {
      cout<<"Destructor function of class C"<<endl;
    }
};
int main()
{
  C c1;
  B b1;
  return(0);
}


Output:

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