虚析构函数

虚析构函数

@(C++实践)

很多书里都有说过,要把基类的析构函数声明为virtual,那么为什么呢?
看下面这个例子:

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

    virtual void fun()
    {
        std::cout << "Base::fun()" <<  std::endl;
    }
};
class Derived : public Base                              
{                                                        
public:                                                  
    Derived()                                            
    {                                                    
        std::cout << "Derived::Derived()" <<  std::endl; 
    }                                                    
    ~Derived(){                                          
        std::cout << "Derived::~Derived()" <<  std::endl;
    }                                                    
    void fun()                                           
    {                                                    
        std::cout << "Derived::fun()" <<  std::endl;     
    }                                                    
};  

int main(int argc, const char* argv[]) 
{                                      
    Base* pb = new Base();             
    Base* pd = new Derived();          
    pb->fun();                         
    pd->fun();                         
    delete pb;                         
    delete pd;                         
    return 0;                          
}                                                     

程序看似没有什么问题,new的指针都delete掉了,但是执行起来:

Base::Base()
Base::Base()
Derived::Derived()
Base::fun()
Derived::fun()
Base::~Base()
Base::~Base()

怎么delete pd这个指针只调用了基类的析构函数啊。这岂不是个天坑。
对此只要把基类的析构函数声明为virtual即可,看下虚析构函数下的输出结果:

Base::Base()
Base::Base()
Derived::Derived()
Base::fun()
Derived::fun()
Base::~Base()
Derived::~Derived()
Base::~Base()

delete pd的时候,它很机智的先执行了派生类的析构函数,然后执行了基类的析构函数。

你可能感兴趣的:(C++)