#include <iostream> using namespace std; class Base { public: Base(){cout<<"Base constructor"<<endl;} ~Base(){cout<<"Base dectructor"<<endl;} }; class Derived : public Base { public: Derived(){cout<<"Derived constructor"<<endl;} ~Derived(){cout<<"Derived destructor"<<endl;} }; int main() { Base * p = new Derived(); delete p; return 1; }
输出结果是:
Base constructor
Derived constructor
Base dectructor
可以很明显的看出,在使用
Base * p = new Derived();
基类指针来生成子类对象的时候,系统可以自动调用子类对象的构造函数。
但是在
delete p;
的时候,p还是一个基类指针,我们观察到子类的析构函数没有被调用,那么就会发生内存泄漏。