Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to explicitly call the base virtual destructor?

Tags:

c++

destructor

When overriding a class in C++ (with a virtual destructor) I am implementing the destructor again as virtual on the inheriting class, but do I need to call the base destructor?

If so I imagine it's something like this...

MyChildClass::~MyChildClass() // virtual in header {     // Call to base destructor...     this->MyBaseClass::~MyBaseClass();      // Some destructing specific to MyChildClass } 

Am I right?

like image 793
Nick Bolton Avatar asked Mar 24 '09 14:03

Nick Bolton


People also ask

Does virtual destructor call base class destructor?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors. you can't have a pure virtual destructor without a body.

Should base class destructor be virtual?

If a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.

Is base class destructor called first?

The body of an object's destructor is executed, followed by the destructors of the object's data members (in reverse order of their appearance in the class definition), followed by the destructors of the object's base classes (in reverse order of their appearance in the class definition).

Why does base class need virtual destructor?

Virtual destructors in C++ are used to avoid memory leaks especially when your class contains unmanaged code, i.e., contains pointers or object handles to files, databases or other external objects.


1 Answers

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.

like image 78
Lou Franco Avatar answered Sep 21 '22 08:09

Lou Franco