C++Tutorials

C++ Destructor

A destructor works opposite to a constructor, it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically.

A destructor is defined as a constructor. It must have the same name as the class. But it is prefixed with a tilde sign (~).

C++ Constructor and Destructor Example

Let’s see an example of constructor and destructor in C++ which is called automatically.

#include <iostream>  
using namespace std;  
class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Constructor Invoked"<<endl;    
        }    
        ~Employee()    
        {    
            cout<<"Destructor Invoked"<<endl;    
        }  
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2; //creating an object of Employee  
    return 0;  
}  

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

Advantages of Destructor in C++

  • It gives the final chance to clean up the resources that are not in use to release the memory occupied by unused objects like deleting dynamic objects, close of the system handles, used files.
  • Because of a lot of resources occupying space and not getting used in the computer, the destructor always comes with a good image to reduce the chances of memory leak by destroying those unused things.
  • Though C++ does have the mechanism of Garbage Collection but calling the destructor automatically whether the programmer calls it or not to free up space prevents the user from many worst situations in the future.

Points to Summarise about Destructor

  • Destructors are used to destroy the unused resources of a class.
  • Destructors have the same name as the class name preceding with (~) sign.
  • Unlike Constructors, there can be no parameter of the destructor.
  • There is no return type of destructor.
  • If the user does not define a destructor by itself in a program, the compiler automatically constructs one destructor for it.
  • There cannot be more than one destructor in a single class.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Back to top button