Destructors in C++

The destructors in C++ can be defined as a member function which destructs or deletes an object. The destructor names are the same as the class name but they are preceded by a tilde (~). And it also a good practice to declare the destructor after the end of using constructor. A destructor function is called automatically when the object goes out of scope i.e.



  • when program ends
  • when a block containing temporary variables ends
  • when a delete operator is called

Destructors in C++

Unlike constructors a destructor neither takes any arguments nor does it returns value. And destructor can’t be overloaded. More than one destructor can’t be used in a program. Only a single destructor is allowed.

Features of destructors

  • The same name as the class but is preceded by a tilde (~)
  • No arguments and return no values

Syntax:

~classname()
{
……
}

Example:

#include <iostream>
using namespace std;
class ABC
{
    public:
        ABC () //constructor defined
       {
 	    cout << "Hey look I am in constructor" << endl;
       }
       ~ABC() //destructor defined
       {
             cout << "Hey look I am in destructor" << endl;
       }
};

int main()
{
     ABC cc1; //constructor is called
     cout << "function main is terminating...." << endl;
     /*....object cc1 goes out of scope ,now destructor is being called...*/
     return 0;
}  //end of program

Output:

Hey look I am in constructor
function main is terminating…
Hey look I am in destructor

Example:

#include<iostream.h>
#include<conio.h>
class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
~sum()
{
cout<<<<endl;"call destructor";
}
delay(500);
};

void main()
{
sum s;
cout<<<<endl;"call main";
getch();
}

Output:

Sum: 30
call main
call destructor