C++中虚析构函数的作用

在C++编程中,一般基类的析构函数设置为虚析构函数。这么做的目的是什么?下面通过例子来说明:

#include <iostream>
using namespace std;

//基类
class base_class
{
public:
	base_class(){};	//构造函数
	virtual ~base_class(){};	//虚析构函数
//	~base_class(){};	
	virtual void test(){ cout << "This is a test in the base class!\n" << endl; };
};

//派生类
class derived_class: public base_class
{
public:
	derived_class(){};
	~derived_class(){ cout << "This is the output from the destructor of derived class!" << endl;};

	void test(){ cout << "This is a test in the derived class!\n" << endl;};
};

//主函数
int main()
{
	base_class *p = new derived_class;
	p->test();
	delete p;

	return 0;
}

当把基类中的析构函数改为非虚函数时,其输出为:



当把基类中的析构函数改为虚函数时,则其输出为:


从以上对比可以看出,若基类没有使用虚析构函数时,则派生类的析构根本没有被调用。
而我们从C++的语法知识可以,析构函数的作用是释放内存资源,因此若析构函数没被调用,则会造成内存泄露,

因此,可以虚析构函数的作用做是为了当用一个基类的指针删除一个派生类的对象时,派生类的析构函数会被调用。 

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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值