I coded the following classes in order to test the multi-level inheritance concept. There is a point that I didn't really understand when I was trying to test the calls to constructors and destructors.
#include <iostream>
using namespace std;
class X{
public:
X(){cout <<"Construct X " << endl;};
virtual ~X(){cout <<"Destruct X " << endl;};
virtual void print() const = 0;
};
class Y: public X{
public:
Y(){cout <<"construct Y " << endl;};
~Y(){cout <<"Destruct Y " << endl;};
void print() const{
cout <<"print Y" << endl;
};
};
class Z: public Y{
public:
Z(){cout <<"Construct Z" << endl; };
~Z(){cout <<"Destruct Z " << endl; };
void print() const{
cout <<" Print Z" << endl;
};
};
int main()
{
Y y;
//Why isn't Y being destructed in here
Z z;
return 0;
}
Output
The output is the following. I understood that we start from the base class. So in Y y;
first the constructor of X is called, then Y. In Z z;
first the construct of X is called, then Y and finally Z.
Construct X
construct Y
Construct X
construct Y
Construct Z
Destruct Z
Destruct Y
Destruct X
Destruct Y
Destruct X
Question
Why isn't the destructor for Y being called right after
Y y;
. Why should we wait till Z is constructed then call the destructors. Meaning why doesn't the output look like that:Construct X construct Y Destruct Y Destruct X Construct X construct Y Construct Z Destruct Z Destruct Y Destruct X