基类的析构函数为什么要设置成virtual

今天在一场面试过程中碰到这个问题,当时一时片刻没有反应过来,一头雾水。只记得自己回到说,是会造成内存泄露,但面试穷追猛打,一直追问为什么造成内存泄露,还给举例说明,一般情况下是不会造成内存泄露的,搞得场面很尴尬。回来后,心有不甘,上机看看到底存在不存在这个问题。

#include <iostream>
using namespace std;

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

class Derived : public Base
{
    public:
        Derived():Base(){
            cout<<"Derived::Derived"<<endl;
            buf = new char[1024];
        }
        ~Derived() {
            cout<<"Derived::~Derived"<<endl;
            delete[] buf;           
        }
    private:
        char* buf;
};


int main()
{
    Base* a = new Derived();
    delete a;

    return 0;
}

运行结果

Base::Base
Derived::Derived
Base::~Base

果然没有释放掉继承类的析构函数,好了。当我把基类的析构函数改为virtual的情况又如何呢?

#include <iostream>
using namespace std;

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

class Derived : public Base
{
    public:
        Derived():Base(){
            cout<<"Derived::Derived"<<endl;
            buf = new char[1024];
        }
        ~Derived() {
            cout<<"Derived::~Derived"<<endl;
            delete[] buf;           
        }
    private:
        char* buf;
};


int main()
{
    Base* a = new Derived();
    delete a;

    return 0;
}

运行结果

Base::Base
Derived::Derived
Derived::~Derived
Base::~Base

结论

为什么会是这样呢? 先补充一个知识, 派生类构造函数和析构函数都会调用基类的构造函数和析构函数,而且顺序是基类的构造函数先调用,析构的时候基类的析构函数最后调用,从上面例子输出中也能看出来。 还有最重要的一点就是virtual就是为多态准备的,只有加上virtual的声明的函数,才能实现多态特性,对普通函数我们很好理解,但对于特殊的函数比如析构函数,也是一样的,只不过它不是同名函数,但具有的性质是一样的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值