I'd like to know what's the correct way to implement virtual destructors when dealing with multilevel inheritance.
So let me introduce this simple example:
#include <iostream>
using namespace std;
struct A {
virtual ~A() { cout << "~A()" << endl; }
};
struct B : A {
~B() { cout << "~B()" << endl; }
};
struct C : B {
~C() { cout << "~C()" << endl; }
};
struct D : B {
~D() { cout << "~D()" << endl; }
};
int main() {
A* a = new C();
B* b = new D();
delete a;
delete b;
}
So afaik, when the base class declares its destructor as virtual it will call correctly the destructor of its children when it gets deleted. My concern is that when I ran this code in both cases delete a and delete b, the children were destroyed correctly, while I was spectating that only delete a would achieve that.
Is this the correct behavior? If so, does it mean that every child class of A will declare its destructor as virtual even if it's not explicitly specified and I can safely assume they will be deleted correctly?