Abstract classes, inheritance and virtual destructors

João Pires :

Even though B's destructor isn't virtual, I still can call C's destructor through B pointer.

Does this mean that only the only outermost abstract class needs to have a virtual destructor?

And if so, why does it work like this?

Is it becase B is inheriting A's destructor?

#include <iostream>

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

    virtual void
    function_a() = 0;
};

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

    virtual void
    function_b() = 0;
};

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

    void
    function_a() override {
        std::cout << "function_a\n";
    }

    void
    function_b() override {
        std::cout << "function_b\n";
    }
};

int
main() {
    B * b = new C();

    b->function_a();
    b->function_b();

    delete b;
}
songyuanyao :

The destructor of B and C are both virtual too. Destructors won't be inherited, but if the base class' destructor is virtual, the derived destructor overrides it and is also virtual; despite of virtual is specified explicitly or not.

Even though destructors are not inherited, if a base class declares its destructor virtual, the derived destructor always overrides it.

and

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27302&siteId=1