When we use constructor in the C++ program, then it becomes mandatory to use destructor . But why?
why we use destructor?
as we know, the constructor allows us to initialize the class-variable From which we can class, it is user defined data type but initialization like a built in data type.
But where built in data type variables are automatically destroyed by the compiler when going out of scope, it does not happen in the class, due to which the memory space reserved or occupy by the class-variable, even when not needed. For this, we have to use Destructor. The destructor gets invoked by the compiler as soon as the class variable out of scope occurs.
So in a way it can say that destructor is used to release memory of the occupied by a class variable, which means destructor is used for memory utilization.
C++ destructor
just as C++ constructor is used to initialize the class-variable. In the same way C++ Destructor is used to destroy the object initialized by the constructor.
Here is the syntax,
~function-name();
In this, like the constructor, the function-name will be the same as the class name.
Let’s explore it,
Rule for declaring a destructor in C++
- destructor is declared as a constructor in the public section of the class, while definition can be defined in either inside class or outside class (using the resolution operator like other normal members).
- destructor name is the same as class name.
- destructor does not return any kind of value. But it will also not be void data type function.
- The destructor member cannot be inherited, although they can be called from the derive class.
- destructor can not be overloaded.
- The destructor member function is represented by a tild sign (~).
Here in below syntax, where destructor declared in public while definition outside the class using scope resolution operator like normal member,
class class-name
{
public:
~class-name (); // public mode
};
class-name::~class-name()
{
......
......
}
Here is program below,
destructor program in C++
#include<iostream>
using namespace std;
int count = 1;
class execute
{
public:
execute(void); // constructor declaration in public mode
~execute(void); // destructor declaration in public mode
};
execute::execute(void) // constructor defination outside class
{
cout<<"object "<<count++<<" created\n";
}
execute::~execute(void) // destructor defination outside class
{
int t_c = count--;
cout<<"object "<<t_c-1<<" destroyed\n";;
return 0;
}
int main()
{
execute x,y,z; // object declare
cout<<endl;
return 0;
}
OUTPUT
object 1 created
object 2 created
object 3 created
object 3 destroyed
object 2 destroyed
object 1 destroyed
Explanation
For example, here a constructor member object is initializing three objects (x, y, z) and a destructor member is destroying those objects.
Be aware that the destructor member will destroy the object from reverse as shown in output.
Previous – constructor in C++
Next – inheritance and their types in C++