Why is a derived class destructor called?

I have a simple program:

struct B { virtual ~B() {} }; struct D : public B { ~D() {} }; 

So when I call

 B* b = new D; b->~B(); 

why is the destructor of the derived class called? It is virtual, but do we call the destructor by name or is there a hidden name of the destructor that is the same for all classes?

+5
source share
1 answer

The destructor does not have a name as such. For class C ~C C syntax is used to denote a single, nameless destructor.

In your case, ~B therefore simply means "destructor." Since virtual dynamic dispatch occurs at runtime with the D destructor, it is called.

If you did this instead:

 b->B::~B(); 

it will disable dynamic sending (like any other qualified call), and you only call the destructor B

+11
source

All Articles