Destructor is a
member function having same name as that of constructor but it is preceded by a
tilde(~) symbol and is executed automatically when object of a class is
destroyed.
•A destructor doesn`t have a return type, not even void and no arguments
•There is only one destructor in class.
•A destructor doesn`t have a return type, not even void and no arguments
•There is only one destructor in class.
•If you don’t provide a destructor of your own then
the
compiler generates a default destructor
•A destructor can be used to deallocate memory
for an
object and declared in the public section.
•A destructor function is called
automatically when
the object goes out
of scope:
(1) the function ends
(2) the program ends
(3) a block containing temporary variables
ends
(4) a delete operator is called
Need for Destructors
•To de-initialize the objects when they are
destroyed
•To clear memory space occupied by a data member.
Examaple
#include<iostream>
#include<conio.h>
class counter
{
int id;
public:
counter(int i)
{
Id=I;
cout<<“contructor of object with id=”<<id;
}
~counter()
{
cout<<“destructor with id=”<<id;
}
};
void main()
{
counter c1(1);
counter c2(2);
counter c3(3);
cout<<“\n end of
main”;
getch();
}
Output:
constructor of object with
id=1
constructor of object with
id=2
constructor of object with
id=3
End of main
destructor with id=3
destructor with id=2
destructor with id=1
No comments:
Post a Comment