⟩ Do you know what are destructors?
Destructors are complements of constructors. When an object is destroyed, its destructor is automatically called. Destructors are mainly useful for doing the clean up job. E.g. an object may have allocated some memory during its lifetime; destructors are the place where this memory is deallocated. Or an object may need to close some files by releasing its handles which it had previously obtained.
Destructor function has same name as that of a constructor; but the name is preceded by a tilde (‘~’) sign.
We will expand the above example of a stack class to include a destructor:
#include <iostream>
using namespace std;
class stack
{
int top, bottom;
int data[20];
stack() //constructor function
{
top = bottom;
cout <<”Inside Stack Constructor: Stack initializedn”;
}
int stackfull()
{
return ((top == max – 1)?1:0);
}
int stackempty()
{
return (top == bottom)?1:0);
}
void push(int no)
{
if(stackfull())
cout<<”Stack is full”;
else
data[++top] = no;
}
int pop()
{
if(stackempty())
cout<<”Nothing to pop.. Stack is Empty!n”;
else
return(data[top- -];
}
~stack() //destructor function
{
cout <<”Inside Stack Destructor: Stack Destroyedn”;
}
};
int main()
{
int i, no;
stack st; //object is created; hence constructor is invoked- stack initialization done
cout <<”Entered Mainn”;
for(i = 0; i < 10; i++)
st.push(i);
no = s.pop();
cout <<”The popped element is:”<<no << “n”;
return 0;
}// at the end of object’s lifetime, destructor is invoked
The o/p of the program would be:
Entered Main
Inside Stack Constructor: Stack initialized
The popped element is: 9
Inside Stack Destructor: Stack Destroyed
As seen from the o/p the constructors and destructors are automatically called.