In this tutorial, we will learn about the destructors, its difference from constructor with example.
We have a case where if object of class in created then the constructor get called automatically. Similarly there is also case when object of class is destroyed function get called automatically. Such functions are called destructor.
Here, Like constructors, destructors do not have a return value. They also take no arguments.
It does not have any return type same as constructor. It doesn’t take any argument hence cannot be overloaded. So, there will be only one destructor.
If the class does not define a destructor, the compiler will create a destructor as a public member, called the default destructor.
Syntax of destructor
Here, ~ symbols is used to define destructor.
Example of Destructor in C++
/*.....Example to show use of destructor.......... */
using namespace std;
cout << "Constructor called";
cout << "Destructor called";
Demo obj1; // Constructor Called
Demo obj2; // Constructor Called
// Destructor Called for obj2
} // Destructor called for obj1
Here, obj1 and obj2 are created. After these objects goes out of scope, the memory they consumed are deallocated in the manner last-in-first-out. Hence, obj2 is destruct first then obj1.