Destructors in C++

Destructors

Destructors are opposite of Constructors, while constructors initialize the value for an object that is instantiated. Constructors destroy the objects and assigned value to them. Destructors are called when –

  • The object goes out of scope of execution
  • Are automatically called by compiler if are not manually defined by the user

Destructors are special functions of a class

  • Have the same name as the name of the class
  • Are preceded with~ for example for class named as Demo the destructor will be ~Demo()
  • No argument passing or copying happens unlike constructors where we can parameterize or copy

Syntax

class Demo
{
public:
~Demo();
};

Example of a Destructor

#include<iostream>
using namespace std;

class Demo
{
public:
//Initialising the Constructor Destructor
Demo()
{
cout << "Object has been Constructed\n";
}

~Demo()
{
cout << "We have Destroyed the object\n";
}
};

int main()
{
Demo demo;
// Constructor Called
int temp=1;
if(temp)
{
// Constructor calling happens here
Demo prepinsta;
}
// The scope of the object initialised prepinsta has ended here so the destructor will be called automatically by the system.
}
// Destructor called for Demo as demo object's out of scope

Output –

Object has been Constructed

Object has been Constructed

We have Destroyed the object

We have Destroyed the object