Tristan Brindle
Tristan Brindle

Reputation: 16834

Could the implicit destructor of a polymorphic class be made virtual?

As far as I'm aware, it is always a mistake (or at the very least, asking for trouble) to define a class with virtual functions but a non-virtual destructor.

As such (and thinking about the newly-coined "rule of zero"), it seems to me that the implicitly generated destructor should automatically be virtual for any class with at least one other virtual function.

Would it be feasible for some future version of the C++ standard to mandate this? Or to put it another way, are there any good reasons to keep the default destructor non-virtual in a polymorphic class?

EDIT: Just to make it clear, I'm only suggesting what might happen if you don't write a destructor -- if you do write your own, you of course get to choose whether it's virtual or not, as ever. I'd just like to see the default match the common case (without preventing more advanced usage).

Upvotes: 2

Views: 239

Answers (1)

Mark B
Mark B

Reputation: 96291

If you don't want or need to polymorphically delete such objects it's not needed that the destructor be virtual. Instead it can be protected non-virtual in the base class, allowing only to be deleted non-polymorphically. Requiring it to be automatically virtual would then impose an undue cost on applications that don't need polymorphic destruction.

Upvotes: 1

Related Questions