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;
}
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 keywordvirtual
is used in its declaration) and overridesBase::vf
(whether or not the wordoverride
is used in its declaration).