Tags C & C++

To work correctly, classes with virtual methods must also have virtual destructors. Interestingly, virtual destructors can be declared pure, which can be useful in some cases.

Imagine you have a base class you want to make abstract. In this base class all methods have meaningful default implementations, and you want to allow the derived classes to inherit them as-is. However, to make a class abstract, at least one of its methods must be made pure virtual, which means the derived classes must override it. How do you make the class abstract in this case?

The answer is: declare the destructor pure virtual. This will make your class abstract without forcing you to declare any other method pure virtual.

// Abstract base class - can't be instantiated
//
class Base
{
public:
    virtual ~Base() = 0;
    virtual void method();
};

Base::~Base()
{
  // Compulsory virtual destructor definition,
  // even if it's empty
}

void Base::method()
{
  // Default implementation.
  // Derived classes can just inherit it, if needed
}

// We can now derive from Base, inheriting the
// implementation of method()
//
class Derived : public Base
{
public:
    ~Derived()
    {}
};

While defining (providing an implementation) pure virtual methods is rarely useful, you must define a pure virtual destructor. This is because the destructor of a base class is always called when a derived object is destroyed. Failing to define it will cause a link error.


Comments

comments powered by Disqus