Destructor in C++

Introduction

  • Destructor is a type of special member function of a class.
  • It is used to destroy the memory allocated by the constructor.
  • It has the same name as the class prefixed with a tilde (~) sign.
  • Destructor does not take any arguments and cannot return or accept any value.
  • It is called automatically by the compiler when the object goes out of scope.
  • Compiler calls the destructor implicitly when the program execution is exited.
Syntax:
class class_name
{
    public:
       ~class_name();
};

Example : Demonstrating the Destructor

#include <iostream>
using namespace std;
int count=0;
class show
{
     public:
         show()
         {
              count++;
              cout << "Create Object : " << count<<endl;
         }
         ~show()
         {
              cout << "Destroyed Object : " << count<<endl;
              count--;
         }
};
int main()
{
     cout << "Main Objects: a,b,c\n";
     show a,b,c;
     {
          cout << "\n New object: d\n";
          show d;
     }
     cout << "\n Destroy All objects: a,b,c\n";
     return 0;
}


Output:
Main Objects: a,b,c
Create Object : 1
Create Object : 2
Create Object : 3

New object: d
Create Object : 4
Destroyed Object : 4

Destroy All objects: a,b,c
Destroyed Object : 3
Destroyed Object : 2
Destroyed Object : 1

In the above program, constructors show() and destructor ~show() is used.

First three objects a,b,c are created and fourth object d is created inside "{}". The fourth object d is destroyed implicitly when the code execution goes out of scope defined by curly braces ({}). And then, all the existing objects a,b,c are destroyed.