为什么要定义成虚析构函数
来源:互联网 发布:江西自考网络助学 编辑:程序博客网 时间:2024/06/03 19:37
一次面试时考官问的,没有答好。平时只是规则般的把析构函数写成虚函数,但是忘了具体原因,今天复习一下。
class CBase
{
public:
CBase() {};
virtual ~CBase() {cout << "destructor of class CBase" << endl; };
virtual void DoSomething() { cout << "Do something in class CBase!" << endl; };
};
{
public:
CBase() {};
virtual ~CBase() {cout << "destructor of class CBase" << endl; };
virtual void DoSomething() { cout << "Do something in class CBase!" << endl; };
};
class CDerived : public CBase
{
public:
CDerived() {};
~CDerived() { cout << "destructor of class CDerived!" << endl; };
void DoSomething() { cout << "Do something in class CDerived!" << endl; };
};
{
public:
CDerived() {};
~CDerived() { cout << "destructor of class CDerived!" << endl; };
void DoSomething() { cout << "Do something in class CDerived!" << endl; };
};
int main(int argc, char* argv[])
{
CBase *pBase = new CDerived;
pBase->DoSomething();
delete pBase;
return 0;
}
{
CBase *pBase = new CDerived;
pBase->DoSomething();
delete pBase;
return 0;
}
基类析构函数定义为虚函数,是为了析构时能调用派生类的析构函数。否则将会只调用基类析构函数,而跳过派生类析构函数,从而导致内存泄露。
- 为什么要定义成虚析构函数
- 析构函数为什么要定义成虚析构函数?
- 为什么析构函数要定义为虚函数
- C++析构函数为什么要定义成虚函数
- 看到这个你能明白很多为什么要定义new,为什么函数不要定义
- JAVA里面main函数为什么要定义为static的?
- java中的main函数为什么要定义为static的?
- 为什么要将成员函数的声明和定义分开
- C++多态为什么要定义虚析构函数
- 为什么大数组要定义在main函数外
- 为什么要将析构函数定义为虚函数
- 为什么要定义interface
- 为什么要定义接口?
- 为什么要把父类的析构函数定义成虚函数?
- 为什么要把父类的析构函数定义成虚函数
- 为什么要把父类的析构函数定义成虚函数?
- 为什么要把父类的析构函数定义成虚函数?
- 关于父类析构函数为什么要定义为虚函数_boolan_第二门课_第一周
- linux tar.gz 安装方法
- 布里丹的驴子
- C++中的未定义行为(undefined behavior)
- 宏与函数
- 我心目中的牛程序员、我们可以对比看看(人家还是看多年朋友面子上才肯帮忙1周,至少需支付1万元辛苦费)
- 为什么要定义成虚析构函数
- fopen /open,read/write和fread/fwrite区别
- 条件编译
- 一个滚动条样式
- ASP.NET 页生命周期概述
- 记录iphone helloworld 完整的流程,从开发到发布到真机。
- struts2异常处理
- OpenCV中使用cvGetReal2D出现的问题
- 测试驱动开发