Destructor

Destructors in C++
Using Destructors in C++?
How to destroy objects in C++?

Explanation
Destructors are a type of member functions used to destroy the objects of a class created by a "Constructor". The destructors have the same name as the class whose objects are intialized but with a "~" or "tilde" symbol preceding the destructor declaration.
"Destructors" dont take any arguments or neither pass any values. But it is used to free the space used by the program. The C++ compiler calls the destructor implicitly when a program execution is exited.

Example :

#include <iostream.h>
int cnt=0;
class display
{
public:
display()
{
cnt++;
cout << "\nCreate Object::" << cnt;
}
~display()
{
cout << "\nDestroyed Object::" << cnt;
cnt--;
}
};
int main()
{
cout << "\nMain Objects x,y,z\n";
display x,y,z;
{
cout << "\n\nNew object 4\n";
display B;
}
cout << "\n\nDestroy All objects x,y,z\n";
return 0;
}
Result :
Main Objects x,y,z
Create Object::1
Create Object::2
Create Object::3
New objects 4
Create Object::4
Destroyed Object::4
Destroy All objects x,y,z
Destroyed Object::3
Destroyed Object::2
Destroyed Object::1
In the above example both a constructor "display()", destructor "~display()" is used. First three objects x,y,z are created, then a fourth object is created inside "{}". The fourth object is destroyed implicitly when the code execution goes out of scope defined by braces. Finally all the existing
objects are destroyed.

Post a Comment

Previous Post Next Post