Why is the destructor of the derived class called?
Asked Answered
C

1

5

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?

Clymer answered 1/7, 2015 at 8:7 Comment(0)
O
11

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.

Octane answered 1/7, 2015 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.