please consider the following
class base{
base();
~base();
}:
class derived : public base{
};
Does a base class destructor is automatically invoked when a derived object is destructed and the derived class has no destructor defined?
Otherwise, if I have a destructor in the derived class too, do I need to call explicitly base class destructor too?
class base{
base();
~base();
}:
class derived : public base{
derived();
~derived
base::~base(); //do I need this?
}
};
A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
No, destructors are called automatically in the reverse order of construction. (Base classes last).
The destructors of base classes and members are called in the reverse order of the completion of their constructor: The destructor for a class object is called before destructors for members and bases are called. Destructors for nonstatic members are called before destructors for base classes are called.
Destructor of base class should always be static.
The base class destructor is automatically invoked in this case; you do not need to call it.
However, note that 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 declare the destructor as virtual
in any class which is meant to be derived from. If the base class does not need to have a destructor, include a virtual
one anyway with an empty body.
There is an exception to the above rule for an edge case: if your derived classes do not need to support polymorphic destruction, then the destructor does not need to be virtual
. In this case it would be correct to make it protected
instead; more details here, but be advised that this rarely occurs in practice.
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 invoked after the Derived class Destructor, irrespective of Derived class destructor being explicitly 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 will not be any scenario in C++, where one has to explicitly invoke a destructor except while using placement new.
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