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 initialized\n”;
}
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 Destroyed\n”;
}
};
int main()
{
int i, no;
stack st; //object is created; hence constructor is invoked- stack initialization done
cout <<”Entered Main\n”;
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 output 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.
What is a destructor?
A destructor is used to destroy the objects created that have been created by a constructor. It has a same name as its class, just that it is preceded by a tidle.
Explain constructors and destructors.
- Constructors are the member functions of the class that executes automatically whenever an object is created. Constructors have the same name as the class. Constructors initialize the class. Constructors can’t have return type. Destructors are called when the objects are destroyed.
- Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor takes no arguments and has no return type.
What are destructors?
- Destructors are called automatically to destroy the object. There's only one destructor for each object. The name of the destructor is the name of the class, preceeded by a tilde (~).
-
Example :Emp::~Emp()
{
Age = 0;
Sal = 0;
}