C++ Destructors
A Destructor, as the name implies, it is used to destroy the objects that have been created already by a constructor. same Like a constructor, and The destructor is also a member function, whose name is the same as the class name but it is preceded by a tilde symbol
let us take example of the destructor for the class integer can be defined as shown in below
A Destructor never takes any arguments and it is also not return any value. it will be invoked implicitly
by the compiler on exit from the program or(block or function as the case may be) to delete(clean up) storage that is no longer accessible.
It is a good practice to declare destructors in the programs since it releases memory space for the future use.
when new operator is used to allocate memory in the constructors. We should use delete operator to free(delete) that memory.
for example the destroy fro the matrix class discussed above may be defined as follows
Student::~Student()
{
( i=0;i < d1;i++)
{
p[i];
p;
}
|
This is required because when the pointers to objects go out of scope, a destructor is not called implicitly
The example below show that the destructor has been invoked implicitly by the compiler
<iostream>
using namespace std;
count=0;
class ABC
{
:
ABC()
{
count++;
std::cout<< "\n number of object created" <<count;
}
~ABC()
{
std::cout<< "\n No. of objects Destroy" << count;
count--;
}
};
main()
{
std::cout<< "\n\n Enter MAIN \n";
ABC a1,a2,a3,a4;
{
std::cout<< "\n Enter Block1 \n";
ABC a5;
}
{
std::cout<< "\n Enter Block2 \n";
ABC a6;
}
std::cout<< "\n\n Re-enter MAin";
}
|
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 destroy 5
Enter Block2
no. of object created 6
no. of object destroy 6
RE-ENTER MAIN
no. of object destroy 4
no. of object destroy 3
no. of object destroy 2
no. of object destroy 1
|
Note:
As the objects are created and destroyed, they increase the count, notice that after the first group of objects is created, A5 is created and then destroy, A6 is created and then destroyed.
Finally the rest of the objects are also destroyed. When the closing brace of scope is encountered the destroyed of each object in the scope are called.
Note that the object are destroyed in the reverse order of creation.