0
#include<iostream>
using namespace std;
class A
{
protected:
    int a,b;
public:
    A(int i, int j)
    {
        a=i;
        b=j;
        cout<< "A initialized"<<endl;
    }
    ~A()
    {
        cout<< "\nDestructor in base class A"<<endl;
    }
};
class B
{
protected:
    int c,d;
public:
    B(int i, int j)
    {
        c=i;
        d=j;
        cout<< "\nB initialized"<<endl;
    }
    ~B()
    {
        cout<< "\nDestructor in base class B"<<endl;
    }
};
class C : public B, public A
{
    int e,f;
public:
    C(int m, int n, int o, int p, int q, int r): A(m,n), B(o,p)
    {
        e=q;
        f=r;
        cout<< "C initialized";
    }
    ~C()
    {
        cout<< "\nDestructor in derived class C"<<endl;
    }
void display(void)
    {
    cout<< "\nThe value of a is : "<<a;
    cout<< "\nThe value of b is : "<<b;
    cout<< "\nThe value of c is : "<<c;
    cout<< "\nThe value of d is : "<<d;
    cout<< "\nThe value of e is : "<<e;
    cout<< "\nThe value of f is : "<<f;
    }
};
int main()
{
    C objc(10,20,30,40,50,60);
    objc.display();
    return 0;
}

I know Destructors are invoked in the reverse order of the constructor invocation. I would like to know implementation of destructor in above code step by step so i could understand how does this really work. Please specify reason Why and how destructors are invoked in reverse order of the constructor.

Raj
  • 43
  • 1
  • 6

1 Answers1

1

Why? Because it is always safer and logical to deconstructs backwards from the construction. To build a house you first build ground, then walls and roof. If you want to destroy it, you will do it backwards: roof, walls and ground.

How? This is done by the compiler, he knows how to build, then he knows how to destroy. The compiler knows the type of the variable, so its building chain (deduced from inheritance graph and structure composition), then it reverses the chain when it needs to destroy it.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69