虚析构函数

#include<iostream>
using namespace std;
class father
{
public:
   ~father(){cout<<"bye from father"<<endl;};
};
class son:public father
{
public:
    ~son(){cout<<"bye from son"<<endl;};
};
int main()
{
    father *pfther;
    pfther=new son;
    delete pfther;
    return 0;
}

程序行结果为  by from father

也就是没有执行 bye from son

当通过基类的指针删除派生类对象时,通常情况下只调用基类的析构函数,但是当删除一个派生类时,应该先调用派生类的析构函数,然后调用基类的析构函数。

当然并不是把所有类的析构函数都写成虚函数,因为当类里面有虚函数时 编译器会给类添加一个虚函数表,里面用来存放虚函数指针,这样就会增加类的存储空间。所以只有当一个类被用作基类的时候,才把析构函数写成虚函数。

解决方法为 将father 里面的析构函数声明为虚函数 即

  virtual ~father(){cout<<"bye from father"<<endl;};

猜你喜欢

转载自www.cnblogs.com/guoyu1024/p/9068044.html