Search code examples
c++inheritanceoverridingdestructormultiple-inheritance

Override Destructor C++


From the C++ FAQ:

[11.4] Can I overload the destructor for my class? No.

I realize this means you cannot change the return type, arguments' types nor the number of arguments. I may be splitting hairs on the syntax of the words, but is it possible to override the Parent's destructor?

class Child : public Parent {
public:
    virtual Parent::~Parent() {
        // New definition
    }
};

And for that matter do it recursively?

class Grandchild : public Child {
public:
    Child::Parent::~Parent() {
        // An even newer definition
    }
};

I've read this and a related post and it makes me think because destructors are not inherited, they cannot be overridden, but I've never seen it explicitly stated.

EDIT: I changed this to reflect the fact that I want to override the Parent's destructor, note Child and Grandchild overriding ~Parent().

The main reason I am doing this is to maintain Parent's interface while changing the way it is destroyed (the entire reason for the child class). I will have something else managing all Parent's created and will explicitly call their destructors at a later time of my choosing.


Solution

  • I may be splitting hairs on the syntax of the words

    No, you are definitely not – these are two very different things.

    but is it possible to override the destructor?

    Yes, and in fact you must do this in many cases. In order for this to work for a polymorphic object, you need to declare the base class destructor as virtual, though:

    Parent const& p = Child();
    

    Will properly call p.~Child() at the end of scope because Parent::~Parent is virtual.