6
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

q0987
  • 34,938
  • 69
  • 242
  • 387

2 Answers2

7

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • You can declare pure virtual functions with definitions as `inline` (just put the `inline` keyword next to the definition as for any other member function defined outside the class definition); you just can't put the definition in the class definition. – Anthony Williams Mar 10 '11 at 17:57
  • But why it is necessary to define pure virtual destructor – PapaDiHatti Sep 14 '16 at 10:29
-1

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).

M'vy
  • 5,696
  • 2
  • 30
  • 43
  • 1
    A pure virtual function can be defined, ref 10.4/2. – Erik Mar 10 '11 at 17:44
  • Hum I saw this alos [SO](http://stackoverflow.com/questions/630950/pure-virtual-destructor-in-c). Thanks for the tip. Did not know that so far. – M'vy Mar 10 '11 at 17:48
  • 1
    @Mvy, a pure virtual function just enforces that the concrete subclass of it MUST provide a non-pure virtual override implementation. – q0987 Mar 10 '11 at 17:50