class Base { public: virtual ~Base(){ std::out<<"Base Destructor"<<std::endl; } } class Derived: public Base { public : ~Derived(){ std::out<<"Derived Destructor"<<std::endl; } } Base* p=new Derived(); delete p;
class Base { public: virtual ~Base(){ std::out<<"Base Destructor"<<std::endl; } } class Derived: public Base { public : ~Derived(){ std::out<<"Derived Destructor"<<std::endl; } } Base* p=new Derived(); delete p;
Base Destructor
Derived Destructor
Base Destructor Derived Destructor
Derived Destructor Base Destructor
如果析构函数不是虚函数, 而程序执行时又要通过基类的指针去销毁派生类的动态对象, 那么用delete销毁对象时, 只调用了基类的析构函数,未调用派生类的析构函数。 这样会造成销毁对象不完全。