Search code examples
c++destructorderived-classbase-class

need to call the base destructor method from a derived class in c++?


Please consider the following:

class base{
    base();
    ~base();
}:

class derived : public base{

};

Does a base class destructor get automatically invoked when a derived object is destructed when the derived class has no destructor defined?

Otherwise, if I DO have a destructor in the derived class too, do I have to call the base class destructor explicitly?

class base{
    base();
    ~base();
}:

class derived : public base{
     derived();
     ~derived{
           base::~base(); //do I need this?
     }
};

Solution

  • The base class destructor is automatically invoked in this case; you do not need to call it.

    However, note that when destroying an object through delete on a base class pointer and the destructor is not virtual, the result is going to be undefined behavior (although you might not get a crash).

    Always declare the destructor as virtual in any class which is meant to be derived from. If the base class does not need to have a destructor, include a virtual one anyway with an empty body.

    There is an exception to the above rule for an edge case: if your derived classes do not need to support polymorphic destruction, then the destructor does not need to be virtual. In this case it would be correct to make it protected instead; more details here, but be advised that this rarely occurs in practice.