Also read : Can a constructor be private in C++ ?
Predict the output of following programs.
The above program compiles and runs fine. Hence, we can say that : It is not compiler error to create private destructors.
Now, What do you say about below program.
The above program fails in 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 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 malloc() function. Same is implemented in below program.
However, The below program fails in compilation. When we call delete, destructor is called.
We noticed in the above programs, when a class has private destructur, only dynamic objects of that class can be created. Following is a way to create classes with private destructors and have a function as friend of the class. The function can only delete the objects.
What is the use of private destructor?
Whenever we want to control 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. See this for more details.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Virtual Destructor
- Is it possible to call constructor and destructor explicitly?
- Pure virtual destructor in C++
- __attribute__((constructor)) and __attribute__((destructor)) syntaxes in C
- Order of Constructor/ Destructor Call in C++
- Calling virtual methods in constructor/destructor in C++
- Difference Between Constructor and Destructor in C++
- Can we access private data members of a class without using a member or a friend function?
- Can virtual functions be private in C++?
- Can a constructor be private in C++ ?
- Publicly inherit a base class but making some of public method as private
- Difference between Private and Protected in C++ with Example
- How to access private/protected method outside a class in C++
- Draw an ellipse divided by straight line into two colored part in C++ Graphics