简体   繁体   中英

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:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM