With virtual destructors, do I need to explicitly declare a virtual destructor for each subclass?
Asked Answered
G

3

23

I've got a scenario where I'm writing somewhat deep object oriented code, with multiple layers of abstract base classes, and I'm wondering if I have to explicitly declare a destructor for each one.

Will the compiler generate a default one that's already virtual, or will I have to tell it to?

Gravois answered 10/4, 2011 at 6:22 Comment(1)
I note that, in a comment below, you also ask whether you need to define a destructor for each subclass. And that the answer is no.Kaye
H
20

The default destructor is not virtual. If you declare the destructor of your base class as virtual, the destructors of the subclasses will be overrides, and thus also be virtual even without explicitly declaring them to be.

The GNU GCC compiler even gives a warning if you have a class hierarchy and your base class does not declare the destructor to be virtual because you most likely want it to be.

How answered 10/4, 2011 at 6:31 Comment(3)
You probably meant destructor, not constructor.Abettor
gcc only issues a warning if you have a virtual method but the destructor is not virtual. You can perfectly inherit from a class without any virtual methods, which is handy for meta-programming :)Tso
Following this advice, is it reasonable to declare a default destructor as: ~ClassName() override = default From my understanding, the override keyword also implies virtual, but please correct me if wrong! :-)Ruppert
E
5

The answer is no. The only relevant requirement here is that classes with a vtable (i.e., with at least one virtual function) must have at least one a virtual destructor somewhere in their inheritance chain. Typically this means that your fundamental base class will provide an empty virtual destructor.

Eschalot answered 10/4, 2011 at 6:35 Comment(0)
H
3

In general if some function is declared virtual in base class, there is no need to explicitly declare it virtual in subclasses. However it is good practice.

Declaring destructors in subclasses as virtual explicitly doesn't give you any serious advantages, so if you don't wont to write one more virtual, don't do that.

Haftarah answered 10/4, 2011 at 6:27 Comment(1)
Would I need to include a definition in the implementation? That would result in a great deal of empty destructors cluttering up my code.Gravois

© 2022 - 2024 — McMap. All rights reserved.