为什么要定义成虚析构函数

来源:互联网 发布:江西自考网络助学 编辑:程序博客网 时间:2024/06/03 19:37

一次面试时考官问的,没有答好。平时只是规则般的把析构函数写成虚函数,但是忘了具体原因,今天复习一下。

class CBase
{
public:
 CBase() {};
    virtual ~CBase() {cout << "destructor of class CBase" << endl; };
    virtual void DoSomething() { cout << "Do something in class CBase!" << endl; };
};
class CDerived : public CBase
{
public:
 CDerived() {};
    ~CDerived() { cout << "destructor of class CDerived!" << endl; };
    void DoSomething() { cout << "Do something in class CDerived!" << endl; };
};
int main(int argc, char* argv[])
{
 CBase *pBase = new CDerived;
 pBase->DoSomething();
 delete pBase;
 return 0;
}
基类析构函数定义为虚函数,是为了析构时能调用派生类的析构函数。否则将会只调用基类析构函数,而跳过派生类析构函数,从而导致内存泄露。