C++ ― why should we define the pure virtual destructor outside the class definition?

匿名 (未验证) 提交于 2019-12-03 00:48:01

问题:

class Object { public:   ...   virtual ~Object() = 0;   ... };  Object::~Object() {} // Should we always define the pure virtual destructor outside? 

Question: Should we always define the pure virtual destructor outside the class definition?

In other words, it is the reason that we should not define any virtual function inline?

Thank you

回答1:

You can define virtual functions inline. You cannot define pure virtual functions inline.

The following syntax variants are simply not permitted:

virtual ~Foo() = 0 { } virtual ~Foo() { } = 0; 

But this is fully valid:

virtual ~Foo() { } 

You must define a pure virtual destructor if you intend to instantiate it or subclasses, ref 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. If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly- declared) is virtual.



回答2:

A pure virtual function does not have an implementation by definition. It should be implemented by the sub-classes.

If you want to chain the destructor, just keep it virtual (non pure virtual).



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