Destructor : the complement of a constructor is the destructor. This function is called when an object is destroyed. For example, an object that allocates memory when it is created will want to free that memory when it is destroyed. The name of a destructor is the name of its class preceded by a tiled (~).
The destructor function has the following characteristics :
- A destructor function never takes any arguments.
- A destructor function will not return any values.
- Destructor cannot be overloaded.
- Destructors can be made virtual.
- a class destructor is called when an object is destroyed.
- Local objects are destroyed when they go out of scope.
- Global objects are destroyed when the program ends.
For example : program to show the use of destructor:
#include<iostream.h>
#include<conio.h>
class Sample
{
int a;
public :
sample()
{
cout<<"\nconstructor called";
a = 10;
}
void show()
{
cout<<"\na = "<<a;
}
~Sample()
{
cout<<"\nDestructor called";
}
};
void main()
{
sample s;
s.show()
}
Output :
Constructor called
a =10
Destructor called
#include<conio.h>
class Sample
{
int a;
public :
sample()
{
cout<<"\nconstructor called";
a = 10;
}
void show()
{
cout<<"\na = "<<a;
}
~Sample()
{
cout<<"\nDestructor called";
}
};
void main()
{
sample s;
s.show()
}
Output :
Constructor called
a =10
Destructor called

0 Comments