![]() |
VOOZH | about |
Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor 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. If the object is referred after the function call, the reference will become dangling.
Predict the Output of the Following Programs:
The above program compiles and runs fine. Hence, we can say that: It is not a compiler error to create private destructors.
Now, What do you say about the below program?
Output
prog.cpp: In function ‘int main()’:
prog.cpp:8:5: error: ‘Test::~Test()’ is private
~Test() {}
^
prog.cpp:10:19: error: within this context
int main() { Test t; }
The above program fails in the compilation. The compiler notices that the local variable 't' cannot be destructed because the destructor is private.
Now, What about the Below Program?
The above program works fine. There is no object being constructed, the program just creates a pointer of type "Test *", so nothing is destructed.
Next, What about the below program?
The above program also works fine. When something is created using dynamic memory allocation, it is the programmer's responsibility to delete it. So compiler doesn't bother.
In the case where the destructor is declared private, an instance of the class can also be created using the malloc() function. The same is implemented in the below program.
The above program also works fine. However, The below program fails in the compilation. When we call delete, destructor is called.
We noticed in the above programs when a class has a private destructor, only dynamic objects of that class can be created. Following is a way to create classes with private destructors and have a function as a friend of the class. The function can only delete the objects.
Another way to use private destructors is by using the class instance method.
constructor called destructor called
Must Read: Can a Constructor be Private in C++?