33. Destructors

By | September 24, 2021

What is a destructor? 
Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.

The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory.  

Syntax:

~constructor-name();

Properties of Destructor:

  • Destructor function is automatically invoked when the objects are destroyed.
  • It cannot be declared static or const.
  • The destructor does not have arguments.
  • It has no return type not even void.
  • An object of a class with a Destructor cannot become a member of the union.
  • A destructor should be declared in the public section of the class.
  • The programmer cannot access the address of 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 are destructors 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

Example

#include<iostream>
using namespace std;
class Demo {  
 private:    
int num1, num2;  
 public:    
Demo(int n1, int n2) {      
cout<<“Inside Constructor”<<endl;      
num1 = n1;      
num2 = n2;  
 }  
 void display() {    
  cout<<“num1 = “<< num1 <<endl;      
cout<<“num2 = “<< num2 <<endl;  
 }  
 ~Demo() {      
cout<<“Inside Destructor”;    
}
};
int main() {    
Demo obj1(10, 20);  
obj1.display();    
return 0;
}

Output

Inside Constructor
num1 = 10
num2 = 20
Inside Destructor

Can there be more than one destructor in a class? 
No, there can only one destructor in a class with class name preceded by ~, no parameters, and no return type.

When do we need to write a user-defined destructor? 
If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leaks.

Leave a Reply

Your email address will not be published. Required fields are marked *