Code One,
#include <iostream>using namespacestd;classbase{ Public: Base () {}; ~Base () {cout<<"Base destructor."<<Endl; };};classDerive: Publicbase{ Public: Derive () {}; ~Derive () {cout<<"Derive destructor."<<Endl; };};intMainintargcChar**argv) {cout<<"Delete PBase"<<Endl; Base*pbase =NewDerive (); Delete pbase; cout<<"Delete pderive"<<Endl; Derive*pderive =NewDerive (); Delete pderive; return 0;}
Operation Result:
Code two,
#include <iostream>using namespacestd;classbase{ Public: Base () {}; Virtual~Base () {cout<<"Base destructor."<<Endl; };};classDerive: Publicbase{ Public: Derive () {}; ~Derive () {cout<<"Derive destructor."<<Endl; };};intMainintargcChar**argv) {cout<<"Delete PBase"<<Endl; Base*pbase =NewDerive (); Delete pbase; cout<<"Delete pderive"<<Endl; Derive*pderive =NewDerive (); Delete pderive; return 0;}
Operation Result:
Conclusion:
The destructor of the base class is to invoke the destructor of the derived class when the base class pointer to the derived class object is deleted.
Whenever a derived class destructor is called, the destructor of the base class must be called.
question: in the memory layout of C + +, virtual functions are directed by function pointers placed in virtual function tables, which are called indirectly by function pointers. And if a virtual function is defined in a derived class, a pointer to the virtual function of the base class in the virtual function table is replaced by a pointer to the virtual function of the derived class. This enables polymorphism by invoking a derived class function with a base-class pointer.
But the destructor is special, because the destructor of the derived class and the destructor of the base class do not have the same name, so this might not be the case, and you need to delve into it.
Virtual destructor of C + +