昨天看了火狐的源码,看到里面很多,应该说几乎所有的析构函数都申明为虚函数,一时想不起来为啥,就上网查了一下,才知道这样做的作用是:
当你动态申请一个对象时,并且把这个对象的指针赋值给基类,这时当你用这个基类指针释放内存时,就有用了,因为这样可以用多态性原理调用对象实际的析构函数来析构内存。举例代码如下
#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;
}
代码中注释了的析构函数是没有声明为虚函数的情况,大家如果也想测试的话,只要把注释去掉,在把虚析构函数注释起来,就可以对比出他们两的差别了。