Destructor in C++ Programming
OOPs in C++
In this lesson, we will understand what is Destructor in C++ Programming and how to create them along with some examples.
What is Destructor in C++?
Destructor is a unique function whose name is the same as the name of the class but declared with a tilted ~ sign before its name. This function executes automatically whenever an object is going to be destroyed from memory. They are used to release memory allocated for the pointer using the constructor.
Properties of Destructor
- It can't be overloaded like a constructor.
- It does not require any arguments.
- It does not return any value.
- It does not have any return type.
- It is declared as a public function in a class.
Example
#include <iostream>
#include <string.h>
using namespace std;
class data
{
private:
int roll;
char name[30];
float *perc;
public:
// Constructor
data()
{
roll=1;
strcpy(name,"Martin");
perc= new float;
*perc=86.23;
cout<<"Constructor Executed"<<endl;
}
void display()
{
cout<<"Roll: "<<roll<<endl;
cout<<"Name: "<<name<<endl;
cout<<"Percentage: "<<*perc<<endl;
}
// Destructor
~data()
{
// free the allocated memeory for pointer per
delete perc;
cout<<"Destructor Executed";
}
};
int main()
{
data x;
x.display();
return 0;
}
Output
Constructor Executed Roll: 1 Name: Martin Percentage: 86.23 Destructor Executed
In the above example, we have created a class called data and declared three private instance variables in it as roll, name, and a float type pointer variable per. After that, we created a constructor function to initialize those instance variables and allocated float size memory for the pointer variable perc using the keyword new.
After that, we created a destructor function to free the memory allocated for the pointer variable perc using the keyword delete. The destructor function is executed automatically when the main program ends.