[ACCEPTED]-need to call the base destructor method from a derived class in c++?-base-class

Accepted answer
Score: 14

The base class destructor is automatically 11 invoked in this case; you do not need to call it.

However, note that 10 when destroying an object through delete on a base class pointer and the destructor is not virtual, the result is going to be undefined behavior (although you might not get a crash).

Always 9 declare the destructor as virtual in any class 8 which is meant to be derived from. If the 7 base class does not need to have a destructor, include 6 a virtual one anyway with an empty body.

There is 5 an exception to the above rule for an edge 4 case: if your derived classes do not need to support polymorphic destruction, then the destructor does not need 3 to be virtual. In this case it would be correct 2 to make it protected instead; more details here, but be advised that 1 this rarely occurs in practice.

Score: 2

Does a base class destructor is automatically invoked when a derived object is destructed and the derived class has no destructor defined?
Yes, the Base class destructor is automatically 6 invoked after the Derived class Destructor, irrespective 5 of Derived class destructor being explicitly 4 defined or not.

Otherwise, if I have a destructor in the derived class too, do I need to call explicitly base class destructor too?
No, You don't need to. There 3 will not be any scenario in C++, where one 2 has to explicitly invoke a destructor except 1 while using placement new.

Score: 1

No, base destructors are invoked automatically 2 in this case, in much the same way that 1 base constructors are can be invoked automatically.

Note, though, that if you are using polymorphism and destroying through a base pointer, you should make sure that the destructor is virtual otherwise this will break.

Score: 1

You should never invoke a base class destructor from a derived class destructor.

The reason is base class destructor 4 will be then called automatically for the 3 second time and writing destructors in such 2 way that this doesn't cause problem is problematic 1 - see this question.

More Related questions