为什么析构函数常声明为虚函数

       昨天看了火狐的源码,看到里面很多,应该说几乎所有的析构函数都申明为虚函数,一时想不起来为啥,就上网查了一下,才知道这样做的作用是:

       当你动态申请一个对象时,并且把这个对象的指针赋值给基类,这时当你用这个基类指针释放内存时,就有用了,因为这样可以用多态性原理调用对象实际的析构函数来析构内存。举例代码如下

#include "stdafx.h"
#include <iostream>
using namespace std;

class CPen
{
public:
	CPen(int weight) : m_weight(weight)
	{
		cout << "construct Cpen object.\n";
	}
	virtual ~CPen()
	{
		cout << "destruct CPen object\n";
	}
	//~CPen()
	//{
	//	cout << "destruct CPen object\n";
	//}
	void PrintWeight() const
	{
		cout << "weight = " << m_weight;
	}
private:
	int m_weight;
};

class CShape
{
public:
	int m_length;	
	int m_thickness;
	int m_colour;
};

class CPencil : public CPen
{
public:
	CPencil(int weight, int length, int thickness, int colour) : CPen(weight)
	{
		m_shapePtr = new CShape;
		m_shapePtr->m_length = length;
		m_shapePtr->m_thickness = thickness;
		m_shapePtr->m_colour = colour;
		//m_weight = weight; error
		cout << "construct CPencil object.\n";
	}
	~CPencil()
	{
		cout << "destruct CPencil\n";
		delete m_shapePtr;
	}
	void ShowInfo() const
	{
		cout << "I am a pencil: ";
		PrintWeight();
		cout << " length = " << m_shapePtr->m_length << " thickness = " << m_shapePtr->m_thickness
			<< " colour = " << m_shapePtr->m_colour << endl;
	}
private:
	CShape *m_shapePtr;
};

int _tmain(int argc, _TCHAR* argv[])
{
	CPen *penPtr = new CPencil(10, 11, 12, 13);

	((CPencil *)penPtr)->ShowInfo();

	delete penPtr;
	penPtr = NULL;
	getchar();
	return 0;
}

代码中注释了的析构函数是没有声明为虚函数的情况,大家如果也想测试的话,只要把注释去掉,在把虚析构函数注释起来,就可以对比出他们两的差别了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值