What is Destructor in C++ ?
A destructor is the name implies , 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.
Syntax:
~ item( ) { }
- A destructor 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 destructor in a program since it releases memory space for future use.
- A destructor is called automatically at the end of an object’s lifetime
Example:
matrix : : ~ matrix( )
{
for(int i=0; i<11;i++)
delete p[i];
delete p;
}
NOTE: Delete is used to free memory which is created by new.
Example:
#include<iostream.h>
int count=0;
class alpha
{
public:
alpha( )
{
count ++;
cout<<”\n no of object created :”<<endl;
}
~alpha( )
{
cout<<”\n no of object destroyed :” <<endl;
coutnt--;
}
};
int main( )
{
cout<<” \n \n enter main \n:”;
alpha A1,A2,A3,A4;
{
cout<<” \n enter block 1 :\n”;
alpha A5;
{
cout<<” \n \n enter block2 \n”;
alpha A6;
}
}
cout<<\n re-enter main \n:”;
return(0);
}
output:-
enter main
no of object created 1
no of object created 2
no of object created 3
no of object created 4
enter block 1
no of object created 5
no of object destroyed 5
enter block 2
no of object created 5
no of object destroyed 5
re-enter main
no of object destroyed 4
no of object created 3
no of object created 2
no of object created 1
You must log in to post a comment.