Question about pure virtual destructor

孤街浪徒 提交于 2019-11-27 09:30:50

The destructor for the base class must be called when the object is destroyed, so it needs a definition.

As pointed out by Jesse, inherited destructors always get called (they are called for you by the compiler with no way to override this behavior), so it stands to reason that a virtual destructor must have an implementation. So if a pure virtual destructor must have an implementation, what is the difference between a pure virtual destructor and a regular virtual destructor? If your abstract class has only the virtual destructor declared and no other pure virtual methods, making the destructor pure will prevent somebody from being able to instantiate the abstract class.

Tobias

Because the standard says so:

12.4.7 A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined.

The reason for this is that it is called explicitly when an object of a derived class is destroyed.

See also the answers to my previous question: Under what circumstances is it advantageous to give an implementation of a pure virtual function?

Only a virtual dtor can be declared as pure. But then, since you add a declaration, you must implement the body of the dtor. As already mentioned, the destructors call their parent dtor, all up to the chain of inheritance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!