Destructors in C++
* Destructor:-
* When
is destructor called?
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 local variables ends
(4) a delete operator is called
* How
destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~).
Destructors don’t take any argument and don’t return anything.
*FULL
DESCRIPTION ABOUT DESTRUCTOR:-
A
Destructor as the name implies ,is used to destroy the objects have been
created by a constructor. Like a constructor, Destructor is a member function
whose name is the same
as the
class name But it is preceded by tilde(~).
1.
A Destructor never takes any argument nor does it
return any value.it will be invoked implicity by the compiler upon exit
from the program to clean up storage that is no longer accessible.
2. it is
a good practise to declare Destructors in a program since it releases memory
space for future use.
3. Whenever; new is used to Allocate
memory in the constructors. we should use delete to
free that memory.
// cpp program to implement Destructor.
#include<iostream>
using namespace std;
int count=0;
class test
{
public: test()
{
count++;
cout<<"\n constructor msg: object"<<count;
}
~test()
{
cout<<"Destructor msg:"<<count;
count--;
}
};
int main()
{
cout<<"inside main block..";
test T1;
{
cout<<"inside block..";
test T1,T2,T3;
cout<<"\n Leaving block..";
}
cout<<"\n Back inside main block..";
return 0;
}
#include<iostream>
using namespace std;
int count=0;
class test
{
public: test()
{
count++;
cout<<"\n constructor msg: object"<<count;
}
~test()
{
cout<<"Destructor msg:"<<count;
count--;
}
};
int main()
{
cout<<"inside main block..";
test T1;
{
cout<<"inside block..";
test T1,T2,T3;
cout<<"\n Leaving block..";
}
cout<<"\n Back inside main block..";
return 0;
}
* Input/output:-
inside
main block..
constructor msg: object1inside block..
constructor msg: object2
constructor msg: object3
constructor msg: object4
Leaving block..Destructor msg:4Destructor msg:3Destructor msg:2
Back inside main block..Destructor msg:1
constructor msg: object1inside block..
constructor msg: object2
constructor msg: object3
constructor msg: object4
Leaving block..Destructor msg:4Destructor msg:3Destructor msg:2
Back inside main block..Destructor msg:1
* Can there be more than one destructor in a class?
No, there can only one destructor in a class with classname preceded by ~, no parameters and no return type.
* Can
a destructor be virtual?
Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function. See virtual destructor for more details.
You may
like to take a quiz on Destructors.