Destructors In C++ -: C++ also provide another member function called the destructors that destroyed object when they are no longer required.
It is the name implies . It is used to destroy the object that have been created by a constructors. Like the constructors is a member function whose name is the same as the class name but is preceded by a tilde. For example the Destructors for the class integer can be defined as like
-Integer (){}
A destructors never takes any argument nor does it return any value.It will be invoked implicitly by the compiler upon exit from the program to clean up storage that is no longer accessible. It is a good practice to declare destructors in a program since it release memory space for future use.
When New us used to allocated memory in the constructors we should use delete to free that memory. For example
Implementation of Destructors program –
#include<iostream>
using namespace std;
int count =0;
class netnic
{
public :
netnic()
{
count ++;
cout << "\n no of object created " << count;
}
-netnic()
{
count --;
cout << "\n no of object destroyed" << count;
}
};
int main()
{
cout << "\n\n enter main \n;
netnic B1, B2, B3, B4;
{
cout << "\n\n Enter block1 \n";
netnic B5;
}
{
cout << "\n\n Enter block2 \n";
netnic B6;
}
cout << "\n\n reenter main \n";
return 0;
}
The output of this program
enter main
no. of object created 1
no. of object created 2
no. of object created 3
no. of object created 4
enter block1
no. of object created 5
no. of object destroyed 5
enter block2
no. of object created 5
no. of object destroyed 5
reenter main
no. of object destroyed 4
no. of object destroyed 3
no. of object destroyed 2
no. of object destroyed 1
Then we can say destruction is the opposite to the constructors