代码改变世界

c++ 虚拟析构函数

2012-07-09 00:01  youxin  阅读(462)  评论(0编辑  收藏  举报

  

    通过基类指针删除派生类对象,基类又没有虚析构函数,结果不可确定。(派生类的析构函数没有被调用,派生类的对象没有被回收)。

 如下是没有定义虚拟的析构函数。

#include <iostream>
using namespace std;

class Base
{
public:
       Base( void )
       {
             cout << "Base::Base( )" << endl;
       }
       
       ~Base( void ) //基类没有虚析构函数时

       {
              cout << "Base::~Base( )" << endl;
       }
};

class Derived : public Base
{
public:
       Derived( void )
       {
                m_pData = new int;
                cout << "Derived::Derived( )" << endl;
       }
       
       ~Derived( void )
       {
                delete m_pData;
                m_pData = NULL;
                cout << "Derived::~Derived( )" << endl;
       }
private:
        int* m_pData;
};

int main( void )
{
    Derived* pD = new Derived;
    
 	Base* pB = pD;
 	
 	//通过基类的指针去删除派生类的对象,而基类又没有虚析构函数时,结果将是不可确定的。

    //(此处是派生类的析构函数没有被调用。)

 	delete pB;
 	pB = NULL;
    
 	system( "PAUSE" );
 	return EXIT_SUCCESS;
}
/*-------派生类的析构函数没有被调用,当然派生类的对象没有被回收
Base::Base( )
Derived::Derived( )
Base::~Base( )
请按任意键继续. . .

如果加上virtual ,就会输出:
/*-------派生类的析构函数没有被调用,当然派生类的对象没有被回收
Base::Base( )
Derived::Derived( )
Derived::~Derived() Base::~Base( ) 请按任意键继续. . .