Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 504
alexgolec Avatar asked Apr 10 '11 06:04

alexgolec


People also ask

Do I need to declare virtual destructor?

Virtual keyword for destructor is necessary when you want different destructors should follow proper order while objects is being deleted through base class pointer.

Do you have to declare a destructor?

No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.

What is the use of declaring virtual destructor under multiple inheritances?

In simple terms, a virtual destructor ensures that when derived subclasses go out of scope or are deleted the order of destruction of each class in a hierarchy is carried out correctly. If the destruction order of the class objects is incorrect, in can lead to what is known as a memory leak.

Is it a good practice to declare the base class destructor always virtual?

However, virtual destructors do not make much sense for classes that are not designed to be base classes (a trait that can be enforced with the final identifier since C++11). In general, blindly declaring every destructor as virtual is a bad practice and can potentially lead to a significant waste of resources.


1 Answers

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.

like image 96
trenki Avatar answered Sep 21 '22 17:09

trenki