Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected vs Private Destructor

Tags:

c++

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.

like image 245
doron Avatar asked Jul 14 '10 13:07

doron


People also ask

Should a destructor be public or private?

C. 35: A base class destructor should be either public and virtual, or protected and nonvirtual.

When should a destructor be private?

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.

Should virtual destructors be protected?

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.

What happens if we make destructor private in C++?

Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.


2 Answers

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.

like image 158
Abhay Avatar answered Sep 29 '22 04:09

Abhay


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).

like image 33
Amir Rachum Avatar answered Sep 29 '22 05:09

Amir Rachum