1.当通过基类指针来删除派生类对象时,如果基类的析构函数不是虚函数,如下例所示:
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base constructed!"<<endl;
}
~Base()
{
cout<<"Base Deconstructed!"<<endl;
}
};
class Derived: public Base
{
public:
Derived()
{
cout<<"Derived constructed!"<<endl;
}
~Derived()
{
cout<<"Derived deconstructed!"<<endl;
}
};
void main(void)
{
Base *pDe=new Derived;
delete pDe;
}
此时输出为:
Base constructed!
Derived constructed!
Base Deconstructed!
可以发现,结果中没有出现派生类对象的析构,那么就会出现内存泄露的情况。所以此时需要将基类的析构函数改为虚函数,派生类对象的析构函数才会被调用。
即改为
virtual ~Base(){....}
上例中,析构函数互为虚函数,但是析构函数的名字不同,之所以基类析构函数为虚,子类析构函数也为虚是因为类中析构函数只有一个,系统默认能成为覆盖的关系。
在Base *pDe=new Derived中,是用基类指针来调用子类函数,从而能实现多态的调用。而不用Derived *pDe=new Derived;
2.重载和覆盖
两者共同点就是函数名相同。
不同点:
a.重载是在同一个类中定义的成员函数,而覆盖是在基类和派生类中定义的函数,作用域不同。
b.重载的返回值、参数列表不同;而覆盖的返回值、参数列表都要求相同
c.覆盖函数前必须加关键字virtual。