C++ Tutorial C++ Advanced C++ References

C++ - Destructors



A destructor is a special member function of a class which destructs or deletes an object and automatically executed when the object goes out of scope. An object goes out of scope when:

  • the function containing object ends.
  • the program ends.
  • a block containing local object variable ends.
  • a delete operator is called for an object.

Create Destructor

To create a destructor in C++, there are certain rules which need to be followed:

  • Destructor should begin with tilde sign(~) followed by class name.
  • A class can have only one destructor.
  • Unlike constructors that can have parameters, destructors do not allow any parameter.
  • Destructor do not have any return type, just like constructors.
  • When a destructor is not specified in a class, compiler generates a default destructor and inserts it into the code.

Syntax

//Defining destructor inside the class
~className() {
  statements;
}

//Defining destructor outside the class
className::~className() {
  statements;
}

Example:

In the example below, a class called Circle is created. A constructor and destructor are also created. The destructor prints a message before deleting the object and called automatically when a object goes out of scope (program ends in this example).

#include <iostream>
using namespace std;
 
class Circle {
  public:
    int radius;
    float area() {
      return 22/7.0*radius*radius;
    }
    Circle(int);
    ~Circle();
};
//constructor definition
Circle::Circle(int x) {
  radius = x;
}
//destructor definition
Circle::~Circle() {
  cout<<"Destructor invoked.\n";  
}

int main (){
  Circle Cir1(5);
  Circle Cir2(10);

  cout<<Cir1.area()<<"\n";
  cout<<Cir2.area()<<"\n"; 
  return 0;
}

The output of the above code will be:

78.5714
314.286
Destructor invoked.
Destructor invoked.