Search code examples
c++polymorphismdestructorvirtual-destructor

Do I need to implement my own destructors for my derived classes if they don't contain static data?


Let's say I have:

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

class Derived: public Base {
public:
    ~Derived();
}

In my code I need to delete Derived classes through a Base pointer, like this:

delete[] pt_base;

However, I don't actually have anything to destroy in the implemented destructors. But I still need them to delete through the base class?

What's the best way to achieve what I want without a whole lot of wasted code and empty destructors?


Solution

  • No, virtual destructor declaration/definition of the Base class is sufficient, though making it abstract requires you give this destructor in the Derived class.

    If you just declare

    class Base {
    public:
        virtual ~Base() {} // <<< Have a definition
    };
    

    you don't need to specify any destructors in inherited classes.