The Wayback Machine - https://web.archive.org/web/20240930224417/https://www.geeksforgeeks.org/private-destructor-in-cpp/
Open In App

Private Destructor in C++

Last Updated : 17 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 

CPP




// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
 
class Test {
private:
    ~Test() {}
};
int main() {}


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? 

CPP




// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
 
class Test {
private:
    ~Test() {}
};
int main() { Test t; }


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? 

CPP




// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
 
class Test {
private:
    ~Test() {}
};
int main() { Test* t; }


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? 

CPP




// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
 
class Test {
private:
    ~Test() {}
};
int main() { Test* t = new Test; }


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. 

CPP




// CPP program to illustrate
// Private Destructor
 
#include <bits/stdc++.h>
using namespace std;
 
class Test {
public:
    Test() // Constructor
    {
        cout << "Constructor called\n";
    }
 
private:
    ~Test() // Private Destructor
    {
        cout << "Destructor called\n";
    }
};
 
int main()
{
    Test* t = (Test*)malloc(sizeof(Test));
    return 0;
}


The above program also works fine. However, The below program fails in the compilation. When we call delete, destructor is called. 

CPP




// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
 
class Test {
private:
    ~Test() {}
};
 
// Driver Code
int main()
{
    Test* t = new Test;
    delete t;
}


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.  

CPP




// CPP program to illustrate
// Private Destructor
#include <iostream>
 
// A class with private destructor
class Test {
private:
    ~Test() {}
 
public:
    friend void destructTest(Test*);
};
 
// Only this function can destruct objects of Test
void destructTest(Test* ptr) { delete ptr; }
 
int main()
{
    // create an object
    Test* ptr = new Test;
 
    // destruct the object
    destructTest(ptr);
 
    return 0;
}


Another way to use private destructors is by using the class instance method. 

C++




#include <iostream>
 
using namespace std;
 
class parent {
    // private destructor
    ~parent() { cout << "destructor called" << endl; }
 
public:
    parent() { cout << "constructor called" << endl; }
    void destruct() { delete this; }
};
 
int main()
{
    parent* p;
    p = new parent;
    // destructor called
    p->destruct();
 
    return 0;
}


Output

constructor called
destructor called

Must Read: Can a Constructor be Private in C++? 
 



Previous Article
Next Article

Similar Reads

Difference Between Constructor and Destructor in C++
Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with argument
3 min read
How to detect Stack Unwinding in a Destructor in C++?
What is Stack Unwinding? Stack unwinding is the process of executing destructors for all local objects when an exception propagates out of a function. It happens when an exception is thrown and not caught within the same function. When this occurs, the destructors for all objects with automatic storage duration declared in that function are called
4 min read
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // CPP program without virtual destructor // causing u
2 min read
Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read
Pure Virtual Destructor in C++
A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you m
4 min read
Order of Constructor/ Destructor Call in C++
Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that t
4 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Publicly inherit a base class but making some of public method as private
There are certain situation when we want to make some of the public base class functions as private in the derived class. Suppose both base and child class has getter and setter methods // CPP program to demonstrate that all base // class public functions become available // in derived class if we use public inheritance. #include <iostream> u
3 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Can a constructor be private in C++ ?
Prerequisite : Constructors A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ? Answer : Ye
3 min read
Difference between Private and Protected in C++ with Example
Protected Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example: [GFGTABS] CPP // C++ program to demonstrate // protected access modifier #include &lt;
3 min read
Can Virtual Functions be Private in C++?
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example 1: Calling Private Virtual Function from Base Class Pointer to Derived Class Instance [GFGTABS] C++ // C++ progr
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Article Tags :
Practice Tags :