Search code examples
c++ooppure-virtualvirtual-destructor

why we are not obliged to implement pure virtual destructor?


making a class abstract is by making one of its member functions pure virtual function.

making a class abstract oblige children of the class to implement the base pure virtual function.

we can even make base class destructor pure and this is enough to be abstract class.

the question:

  • why we are not obliged to implement the pure virtual base's destructor in our derived class?

  • does it mean as long as C++ adds to us four member functions by default: constructor, copy constructor, assignment and Destructor we don't need to implement it in our derived class?

eg:

#include <iostream>
using namespace std;

class Base
{
    public:
        Base(){cout << "Base Ctor" << endl;}
        virtual ~Base() = 0 {cout << "Virtual base dtor" << endl; }
};

class Derived : public Base
{
    public:
        Derived(){cout << "Derived Ctor" << endl;}
         // virtual ~Derived() {cout << "Virtual Derived dtor" << endl; }
};

int main()
{

    Base* theBase = new Derived;
    delete theBase;

    cout << endl;


    cout << endl << endl;
    return 0;
}
  • I know that I should add child destructor to free memory if it was dynamically allocated.

Solution

  • why we are not obliged to implement the pure virtual base's destructor in our derived class?

    Because destructors are not overridden.

    To help remember that, think about the names: ~Base and ~Derived are not the same. Constructors and destructors, instead of working through overriding, are instead called in a chain: the bottom-most destructor runs and then it calls its parent destructor which then runs and then calls its parent destructor etc.

    And that is why you must provide the body for a destructor if you want to delete an instance of one of the derived classes, even if it's marked as pure virtual: it needs a body to invoke when reaching it in the destructor chain.

    So, what's the deal with virtual destructors to start with? It's done so that the compiler would know to invoke the bottom-most destructor when it encounters a destruction of some class. So destruction does use the virtual table, it's just that it's running the parent class destructor after the derived destructor is done, so it's not standard overriding.

    does it mean as long as C++ adds to us four member functions by default: constructor, copy constructor, assignment and Destructor we don't need to implement it in our derived class?

    Didn't quite understand the question, but in any case default-added methods are not created pure virtual and can be created in every class in an inheritance chain.