Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the destructor of the derived class 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'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?

like image 966
user1289 Avatar asked Jul 01 '15 08:07

user1289


People also ask

Why is destructor of derived class called first?

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.

When destructor of a class is called?

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).

Why the name of destructor is same as class name?

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.


1 Answers

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.

like image 102
Angew is no longer proud of SO Avatar answered Nov 03 '22 20:11

Angew is no longer proud of SO