#include "stdafx.h" #include <iostream> using namespace std; class Base { public: Base(){cout << " Constructor in Base. " << endl;} virtual ~Base(){ cout << " Destructor in Base. " << endl;} }; class Derived:public Base { public: Derived(){cout << " Constructor in Derived. " << endl;} ~Derived(){cout << "Destructor in Derived. " << endl;} }; int _tmain(int argc, _TCHAR* argv[]) { Base *p = new Derived; delete p; return 0; }
输出: Constructor in Base. Constructor in Derived. Destroctor in Derived. Destroctor in Base.
如果Base中的析构函数,没有virtual修饰,输出为: Constructor in Base. Constructor in Derived. Destroctor in Base. 这样子类Derived中的析构函数没有执行,会造成内存泄露,因此,如果一个类是其他类的基类,应该将其析构函数声明为虚析构函数。另外从本例中也可以看出,构造函数、析构函数的执行顺序。构造函数,先基类后子类,析构函数,先子类,后基类。