- 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.
for(int i = 0 ; i < r; i++)
- The following is an example showing the use of destructor:
/* Program to demonstrate the use of destructor. */
public : // Constructor to create an object
cout << "Object is created\n";
cout << "Enter your object number : ";
cin >> objno;
// Destructor to destroy an object
cout << "Object is deleted\n";
cout << "Object number = " << objno << endl;
}; // Class ends
cout << "Main program starts\n";
destructor d1, d2;
cout << "Inside block-1\n";
cout << "Inside block-2\n";
cout << "Exit main program\n";