Q20. What is a Destructor? Explain.
Answer:
Destructor
A destructor is a special member function that is used to destroy the objects created by constructor. It takes the same name as the class but with a ‘tilde’ (~) at the beginning. It doesn’t have any return type. It is called automatically at the end of program execution to free up the acquired storage.
Memory allocation is done by using new operator in a constructor whereas delete operator is used in a destructor to deallocate the previously allocated memory.
Example
Destructor
A destructor is a special member function that is used to destroy the objects created by constructor. It takes the same name as the class but with a ‘tilde’ (~) at the beginning. It doesn’t have any return type. It is called automatically at the end of program execution to free up the acquired storage.
Memory allocation is done by using new operator in a constructor whereas delete operator is used in a destructor to deallocate the previously allocated memory.
Example
#include<iostream.h>
#include<conio.h>
class Demo
{
private:
int data;
public:
Demo( )
{
cout<<endl<<“Inside
constructor”;
}
~Demo( )
{
cout<<endl<<“Inside
destructor”:
}
};
void main( )
{
Demo d;
getch( );
}
Output