Is there any difference between a protected and a private destructor in C++? If a base classes destructor is private, I imagine that it is still called when deleting the derived class object.
C. 35: A base class destructor should be either public and virtual, or protected and nonvirtual.
What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destructor private. For dynamically created objects, it may happen that you pass a pointer to the object to a function and the function deletes the object.
So if you don't want callers to do delete bar / delete foo and want both base and derived classes' destructors to be invoked, both destructors must be protected and at least the Base class' destructor must be virtual.
Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.
If the base class destructor is private
or protected
then you cannot call delete
through the base-class pointer.
Use a protected destructor to prevent the destruction of a derived object via a base-class pointer. It limits access to the destuctor to derived classes. And it prevents automatic (stack) objects of class base.
In effect it is used to allow any other polymorphic use of derived classes via pointers to base, but not allow the users to delete using such a pointer. Example:- Abstract Base Classes / Interfaces.
But a protected
, non-virtual
destructor on a non-final
class seems to be a bug waiting to happen. Assuming you do not provide a destroy()
function, you have to eventually make the dtor public. As soon as you do that, you have no further control over the class, and run the risk of polymorphic deletion with a non-virtual dtor, if someone derives further from your class.
Taken from here:
If the constructor/destructor is declared as private, then the class cannot be instantiated.
This is true, however it can be instantiated from another method in the class. Similarly, if the destructor is private
, then the object can only be deleted from inside the class as well. Also, it prevents the class from being inherited (or at least, prevent the inherited class from being instantiated/destroyed at all).
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