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?
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.
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.
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).
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.
No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With