Virtual Destructors

Is-A Relationships And Destructors

  • From Destructors And Inheritance: simple/naive destructors are not enough when using object polymorpically

  • Much like simple/naive methods vs. virtual methods

  • virtual destructors, starting at the root of inheritance

  • dynamic dispatch to destructor of concrete object’s class

  • ⟶ correct cleanup

#include <iostream>


class Base
{
public:
    virtual ~Base()             // <--- Preparing polymorpic usage of derived classes
    {
        std::cout << "Base::~Base()" << std::endl;
    }
};

class Derived : public Base
{
public:
    virtual ~Derived()          // <--- "virtual" not strictly necessary, but good style
    {
        std::cout << "Derived::~Derived()" << std::endl;
    }
};

int main()
{
    Base* b = new Derived;      // <--- Base* points to Derived object
    delete b;                   // <--- Polymorphic usage: entering cleanup at Derived::~Derived()

    return 0;
}
$ ./inher-oo-dtor-derived-virtual
Derived::~Derived()
Base::~Base()

Pure Virtual Destructor?

  • Object destruction calls every destructor up to the innermost base class

  • ⟶ Destructors cannot be pure virtual

#include <iostream>


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

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

int main()
{
    Derived d;

    return 0;
}
inher-oo-dtor-pure-virtual.cpp:15: undefined reference to `Base::~Base()'
collect2: error: ld returned 1 exit status