using namespace std;
class C
{
int a;
public:
C(int aa=0) {a=aa;}
~C() {cout << "Destructor C!" << a << endl;}
};
class D: public C
{
int b;
public:
D(int aa=0, int bb=0): C(aa) {b=bb;}
~D() {cout << "Destructor D!" << b << endl;}
};
void test()
{
D x(5);
D y(6,7);
}
int main()
{
test();
}
Above is the code, and below is the running result:
Destructor D!7
Destructor C!6
Destructor D!0
Destructor C!5
I don’t understand why “Destructor C!” will be invoked. And the related destructor’s calling sequence. I feel that it seems like the stack push/pop.
Further:
Why it calls “D x(5);” earlier but the corresponding result is given later?
The destructor calling sequence always goes from the derived to base, like popping the stack. This allows derived classes to clean up resources allocated by your base class. In this case, the compiler knows how to construct this sequence, because it knows the exact type of the objects
xandystatically.There are situations, however, when this sequence would be broken. Consider the following modification of your code:
It produces the following output:
Running this produces no call of
~Dforx; fory, both destructors are called.This is because you did not declare the destructor
virtualin the base class. When the destructor is not virtual, the compiler has no idea that it must call the destructor of the derived class in situations when an object is referred to by a pointer to a base class. This is why you should always make a destructor virtual in classes that must be inherited and allocate resources dynamically.