|
Whenever an object goes out of scope, it is destroyed. The memory used by that object is reclaimed. Just before the object is destroyed, an object's destructor is called to allow any clean-up to be performed.
A dectructor, as the name suggests, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde sign(~). For example, the destructor for the class number can be defined as shown below:
~number() { }
A destructor does not take any arguments; neither does it return any value. It is invoked implicitly by the compiler upon exit from the program (or a block or a function as the case may be) to clean up storage that is no longer accessible. It is a good practice to declare destructors in a program since this practice releases memory space for future use.
whenever the operator new is used to allocate memory for constructors, we should use the operator delete to free that memory.
The destructor must release any resources obtained by an object during its lifetime, not just those that were obtained during construction.
Characteristics of Destructors
You should be able to provide a destructor for your classes. Do not let the compiler generate it for you.
A program to keep count of objects created and destroyed during run-time.
#include<iostream.h>
int count=0;
class beta
{
public;
beta() //constructor
{
count++;
cout<<"\nObject No:"<<count;
}
~beta() //destructor
{
cout<<"\nObject destroyed:"<<count;
}
};
main()
{
cout<<"\n Main ";
beta B1, B2, B3, B4;
{
cout<<"\n Block1 \n";
beta5; } {
cout<<"\n Block2 \n";
beta6;
}
cout<<"\nBack to main \n";
}
The output of the above program would be:
Main
Object No:1
Object No:2
Object No:3
Object No:4
Block1
Object No:5
Object destroyed:5
Block2
Object No:6
Object destroyed:6
Back to Main
Object destroyed:4
Object destroyed:3
Object destroyed:2
Object destroyed:1
The count increases and decreases as objects are created and destroyed. After the first group of objects are created, object B5 is created and then destroyed, object B6 is created and destroyed. Finally, the rest of the objects are destroyed. The objects are destroyed in the reverse order of their creation.
|