Search code examples
c++abstract-classdestructor

C++ abstract class destructor


Is it good practice (and is it possible) to create an abstract class using only a pure virtual destructor in the parent class?

Here's a sample

class AbstractBase {
public:
    AbstractBase () {}
    virtual ~AbstractBase () = 0;
};

class Derived : public AbstractBase {
public:
    Derived() {}
    virtual ~Derived() {}
};

Otherwise how can I create an abstract class if the attributes and constructors of the derivatives class are all the same while the other method are totally different?


Solution

  • Having only a pure virtual destructor in the base class is rarely a good practice, but it is possible and, in certain cases, even desirable.
    For instance, if you rely on RTTI to dispatch messages to a subclass object by attempting a dynamic_cast on the pointer to the base class, you may need no methods in the base class except the destructor. In this case, make the destructor public virtual.

    Since you have no other virtual methods except the destructor, you have to make it pure in order to prevent the creation of the objects of the base class.
    Here, it is crucial to provide the empty body to that destructor (even though it is "=0"!)

    struct AbstractBase {
         virtual ~AbstractBase() = 0;
    }
    
    AbstractBase::~AbstractBase() {
    }
    

    Having the body allows the creation of subclass objects (provided that the subclass defines the destructor and does not set it as pure).