Search code examples
c++inheritancevirtual-destructor

Why should I declare a virtual destructor for an abstract class in C++?


I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.


Solution

  • It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, then what happens is up to the compiler.

    For example

    class Interface
    {
       virtual void doSomething() = 0;
    };
    
    class Derived : public Interface
    {
       Derived();
       ~Derived() 
       {
          // Do some important cleanup...
       }
    };
    
    void myFunc(void)
    {
       Interface* p = new Derived();
       // The behaviour of the next line is undefined. It probably 
       // calls Interface::~Interface, not Derived::~Derived in
       // which case you have a memory leak. Or it may crash
       delete p;
    }