爲什麼析構函數常聲明爲虛函數

       昨天看了火狐的源碼,看到裏面很多,應該說幾乎所有的析構函數都申明爲虛函數,一時想不起來爲啥,就上網查了一下,才知道這樣做的作用是:

       當你動態申請一個對象時,並且把這個對象的指針賦值給基類,這時當你用這個基類指針釋放內存時,就有用了,因爲這樣可以用多態性原理調用對象實際的析構函數來析構內存。舉例代碼如下

#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;
}

代碼中註釋了的析構函數是沒有聲明爲虛函數的情況,大家如果也想測試的話,只要把註釋去掉,在把虛析構函數註釋起來,就可以對比出他們兩的差別了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章