Destructor
A ‘destructor’ as the name implies, 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 (~). A destructor is a function that automatically executed when an object is destroyed. Destructor functions get executed whenever an instance of the class to which it belongs goes out of existence. The primary usage of the destructor is to release space on the heap. A destructor function may be invoked explicitly. Rules for writing a destructor function are:
· A destructor function name is the same as that of the class it belongs except that the first character of the name must be tilde (~).
· It is declared with no return types (not even void) since it cannot ever return a value.
· It cannot be declared static.
· It takes no arguments and therefore cannot be overloaded.
· It should have public access in the class declaration.
Syntax:
~className()
{…..
…..}
Example:
class desTest
{ private:
int a;
public:
desTest()
{ cout<<"\nI am within Constructor";
a=100; }
|
{ cout<<"\nI am within Destructor";}
void display()
{cout<<"\nValue of data is:"<<a;}
};
void main()
{ desTest ob;
ob.display(); }
Another Example:
int count=0;
class alpha
{
public:
alpha() //constructor function declaration
{ count++;
cout<<"\nNumber of object created "<<count; }
~alpha() //destructor function declaration
{
cout<<"\nNumber of object destroyed "<<count;
count--; }
};
void main()
{
cout<<"\n\n Enter Main \n";
{
alpha a1,a2,a3,a4;//creation of the objects
{
cout<<"\n\nEnter Block1\n";
alpha a5;
}
{
cout<<"\n\nEnter Block2\n";
alpha a6;
}
cout<<"\n\nRe-Enter Main\n";
}
}
As the objects are created and destroyed, they increase and decrease the count. Notice that after the first group of objects is created, a5 is created, and then destroyed; a6 is created, and then destroyed. Finally, the rest of the rest of the objects are also destroyed. When the closing braces of a scope are encountered, the destructors for each object in the scope are called. Note that the objects are destroyed in the reverse order certain.
No comments:
Post a Comment