Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading