Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

like image 258
q0987 Avatar asked Mar 10 '11 17:03

q0987


1 Answers

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.

like image 168
Erik Avatar answered Oct 23 '22 05:10

Erik