This tutorial will teach you about destructors in C++, along with examples to better understand the topic.
In brief, Destructors are used to deallocate memory locations and clean up unwanted resources for a specific class and any members that belong to it. You can call a destructor after a class is no longer needed.
First, let’s create a simple program with destructors defined:
#include <iostream>
using namespace std;
class DestructorsDemo {
int a;
public:
DestructorsDemo() {
a = 0;
cout << "Constructor Called";
}~DestructorsDemo() {
cout << "Destructor Called";
}
void GetValue() {
cout << "Please enter a value of a: ";
cin >> a;
}
void SetValue() {
cout << endl << "The value of a is " << a;
}
};
In the program above, we defined a class DestructorsDemo() and a member a. In C++, the Destructor starts with the symbol ~. It will kill the class instant and all members, in this case, the variable a, when it gets called.
Now, let’s call this program from the main class:
int main()
{
DestructorsDemo destructor;
destructor.GetValue();
cout << endl <<"The value of a in destructor1 is: ";
destructor.SetValue();
DestructorsDemo destructor2;
destructor2.GetValue();
cout << endl <<"The value of a in destructor2 is: ";
destructor2.SetValue();
return 0;
}
Output
Constructor Called Please enter a value of a: 5 The value of a in destructor1 is: The value of a is : 5 Constructor Called Please enter a value of a: 10 The value of a in destructor2 is: The value of a is : 10 Destructor Called Destructor Called
Happy Coding!