- Destructor is a special member function of a class, which is used to destroy the object.
- Like a constructor, it has same name as of class name, but it is preceded by tilde (~) sign.
- A destructor has no argument. Also it doesn’t return any value.
- In dynamic constructor ‘new’ is used to allocate the memory.
- Similarly we can use ‘delete’ to free the memory in destructor.
- In short destructor is used to carry out all the clean up activities at the end of program.
- For example we can create the destructor to delete the memory allocated in matrix.
~matrix( )
{
for(int i = 0 ; i < r; i++)
{
delete p[i];
}
delete p;
}
- The following is an example showing the use of destructor:
/* Program to demonstrate the use of destructor. */
#include "iostream.h"
#include "conio.h"
class destructor
{
int objno;
public : // Constructor to create an object
destructor()
{
cout << "Object is created\n";
cout << "Enter your object number : ";
cin >> objno;
}
// Destructor to destroy an object
~destructor()
{
cout << "Object is deleted\n";
cout << "Object number = " << objno << endl;
}
}; // Class ends
void main()
{
clrscr();
cout << "Main program starts\n";
destructor d1, d2;
{
cout << "Inside block-1\n";
destructor d3;
}
{
cout << "Inside block-2\n";
destructor d4;
}
cout << "Exit main program\n";
getch();
}