c++析构函数必须是虚函数

以前了解析构函数必须是虚构函数,但是一直没有深究到底问什么,今天忽然好奇,做了一些测试才搞明白(猜测)。。。。

先做两个测试

using namespace std;
class father{
    public:
    void print(){
        cout<<"this is father"<<endl;
    }
};
class son :public father{
    public:
    void print(){
        cout<<"this is son"<<endl;
    }
};
int main(){
    son * son1=new son();
    father * father1=static_cast<father *>(son1);
    father1->print();
    return 0;
}

输出为:

this is father
#include<iostream>
using namespace std;
class father{
    public:
    virtual void print(){
        cout<<"this is father"<<endl;
    }
};
class son :public father{
    public:
    void print(){
        cout<<"this is son"<<endl;
    }
};
int main(){
    son * son1=new son();
    father * father1=static_cast<father *>(son1);
    father1->print();
    return 0;
}

输出为:

this is son

可以发现对于非虚函数的成员函数,调用时会执行指针类型的函数。对于virtual修饰的虚函数,调用时只会执行指针指向的实际对象的函数。猜测是由于强转之后虚函数表或者说虚表指针不发生改变,而普通成员函数用过指针类型进行调用的。

以上是子类强转为基类,将基类强转为子类也可以发现相同的结论。

这也就解释了为啥析构函数必须是虚函数,如果不是虚函数,那么如果子类强转为基类,调用的将是基类的函数,而不是子类的,就会析构不完全造成内存泄露。

Ps.结论不严谨,有错误还请指正

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

�Wang Chien Po

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值