Do I need to explicitly call the base virtual destructor?


When overriding a class in C++ (with a virtual destructor) I am implementing the destructor again as virtual on the inheriting class, but do I need to call the base destructor?

If so I imagine it's something like this...

MyChildClass::~MyChildClass() // virtual in header
    // Call to base destructor...

    // Some destructing specific to MyChildClass

Am I right?

3/24/2009 3:52:09 PM

Accepted Answer

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

3/24/2009 2:23:51 PM

No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.

To understand why you want a virtual destructor in the base class, please see the code below:

class B
    virtual ~B()
        cout<<"B destructor"<<endl;

class D : public B
    virtual ~D()
        cout<<"D destructor"<<endl;

When you do:

B *pD = new D();
delete pD;

Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow