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's virtual but we call the destructor by name, or is there a hidden name of the destructor which is the same for all classes?
The derived class must be constructed after the base class so that the derived class constructor can refer to base class data. For the same reason, the derived class destructor must run before the base class destructor. It's very logical: we construct from the inside out, and destroy from the outside in.
A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor is a member function with the same name as its class prefixed by a ~ (tilde).
Like a constructor, Destructor is also a member function of a class that has the same name as the class name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while the object of the class is freed or deleted.
The destructor does not have a name, per se. For a class C
, the syntax ~C
is used to refer to the single, nameless destructor.
In your case, ~B
therefore simply means "the destructor." Because it's virtual, dynamic dispatch happens at runtime at the destructor of D
gets called.
If you did this instead:
b->B::~B();
it would disable dynamic dispatch (like any other qualified call does) and you'd call B
's destructor only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With