C++ Programming - Pure Virtual Destructors

Unlike ordinary member functions, a virtual destructor is not overridden when it is redefined in a derived class. Rather, it is extended. The lower-most destructor first invokes the destructor of its base class; only then is it executed. Consequently, when you try to declare a pure virtual destructor, you might encounter compilation errors, or worse -- a runtime crash. In this respect, pure virtual destructors are exceptional among pure virtual functions -- they have to be defined. You can refrain from declaring a destructor with the pure specifier, making it only virtual. However, this is an unnecessary design compromise. You can enjoy both worlds by forcing an interface whose members are all pure virtual, including the destructor -- and all this without experiencing runtime crashes. How is it done?

First, the abstract class contains only a declaration of a pure virtual destructor:

class Interface
virtual void Open() = 0;
virtual ~Interface() = 0;

Somewhere outside the class declaration, the pure virtual destructor has to be defined as follows:

{} //definition of a pure virtual destructor; should always be empty


About this entry