Home > OS >  Virtual destructor needed for class which is both derived and base?
Virtual destructor needed for class which is both derived and base?

Time:02-24

Say we have the following:

#include <iostream>

struct A
{
    virtual ~A() { std::cout << "destr A\n"; }
};

struct B : A
{
    // no need to be virtual?
    ~B() { std::cout << "destr B\n"; }
};

struct C : B
{
    ~C() { std::cout << "destr C\n"; }
};

Now, I create an instance of C and assign it to a pointer of its base class B.

int main()
{
    B* b = new C{};
    delete b;
    return 0;
}

The output is:

destr C
destr B
destr A

What surprised me a little is that the object gets destroyed correctly (all three destructors are called). According to the output, I would say ~B() is a virtual destructor: ~B() dispatches to ~C(), then ~B() finishes and finally, ~A() is called. Is this statement correct?

I know that, if some function of a base class is virtual, the function in the derived class which overrides the one in the base class is virtual as well. I did not know that was true for destructors as well. Is ~B() virtual because I declared ~A() with the virtual function specifier?

CodePudding user response:

Is ~B() virtual because I declared ~A() with the virtual function specifier?

Yes. Per https://timsong-cpp.github.io/cppwp/n4659/class.dtor#10:

If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.

  • Related