c++ virtual deconstructor
2014-02-27 16:27
309 查看
#include iostream.h class Base { public: Base(){ cout<<"Constructing Base";} // this is a destructor: ~Base(){ cout<<"Destroying Base";} }; class Derive: public Base { public: Derive(){ cout<<"Constructing Derive";} ~Derive(){ cout<<"Destroying Derive";} }; void main() { Base *basePtr = new Derive(); delete basePtr; } |
Constructing Base Constructing Derive Destroying Base |
But there is a major problem with the code above: the destructor for the "Derive" class does not get called at all when we delete ‘basePtr’.
So, how can we fix this problem?
Well, what we can do is make the base class destructor virtual, and that will ensure that the destructor for any class that derives from Base (in our case, its the "Derive" class) will be called.
Subscribe to our newsletter for more free interview questions.
Example with a Virtual Destructor:
So, the only thing we will need to change is the destructor in the Base class and here’s what it will look like – note that we highlighted the part of the code where the virtual keyword has been added in red:class Base { public: Base(){ cout<<"Constructing Base";} // this is a virtual destructor: virtual ~Base(){ cout<<"Destroying Base";} }; |
Constructing Base Constructing Derive Destroying Derive Destroying Base |
So, now you’ve seen why we need virtual destructors and also how they work.
One important design paradigm of class design is that if a class has one or more virtual functions, then that class should also have a virtual destructor.
相关文章推荐
- 详解 C++ virtual 析构函数
- C++ virtual 与"基类"和"派生类"的访问控制
- 读书笔记_Effective_C++_条款三十五:考虑virtual函数以外的其他选择
- 浅析c++中virtual关键字
- 浅析c++中virtual关键字
- 【转载】一篇详尽分析C++“Pure Virtual Function Called”错误的文章
- C++ Virtual详解
- C++ Virtual详解
- C++ virtual 机制
- c++ virtual 虚析构函数 资源释放的讨论
- C++中构造函数和析构函数(virtual)的执行顺序
- 详解 C++ virtual 析构函数
- C++ virtual 关键字详解
- C++的虚基类,抽象类,虚函数,纯虚函数,virtual
- c++ virtual
- C++ - Memory Layout of Virtual Inherit (虚继承的内存布局)
- Virtual Box for ubuntu+emacs for c/c++ IDE
- C++中virtual的三种用法
- C++ virtual member function FAQ
- C++将多态基类的析构函数声明为virtual的作用