Ads block

Banner 728x90px

Destructor in C++

A destructor is a special kind of function that works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically to destroy the objects.

A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~). This is the identification of destructor.

Constructor and Destructor Example

Let's see an example of constructor and destructor in C++ which is called automatically.

#include<iostream.h>

using namespace std;

class Student
{
  public:
     Student()   //Constructor
      {
        cout<<"Student Constructor Invoked"<<endl;
      }
     ~Student()   //Destructor
      {
        cout<<"Student Destructor Invoked"<<endl;
      }
};
int main( )
{
    Student S1;   //S1 Object created
    Student S2;   //S2 Object created
    return 0;
}

Student Constructor Invoked
Student Constructor Invoked
Student Destructor Invoked
Student Destructor Invoked



Some rules of Destructor


Name should begin with tilde sign(~) and must match class name.

There cannot be more than one destructor in a class.

Unlike constructors that can have parameters, destructors do not allow any parameter.

They do not have any return type, just like constructors.

When you do not specify any destructor in a class, compiler generates a default destructor and inserts it into your code.