Destructors in C++

In this tutorial, we will learn about the destructors, its difference from constructor with example.

destructor in c++
fig: constructor and destructor in c++

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.

Structure of destructor

class demo
{
  int a;
public:
    demo ()
  {
    cout << "Constructor called";
  }
   ~demo ()
  {
    cout << "Destructor called";
  }
};

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

 ~class_name ()

Here, ~ symbols is used to define destructor.

Example of Destructor in C++

/*.....Example to show use of destructor.......... */
#include <iostream>
using namespace std;
class Demo
{
Demo()
 {
  cout << "Constructor called";
 }

~Demo()
 {
  cout << "Destructor called";
 }
};

int main()
{
 Demo obj1;   // Constructor Called
    Demo obj2;  // Constructor Called
  // Destructor Called for obj2
} //  Destructor called for obj1

Output

Constructor called
Destructor called

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.