C++ Destructor

destructor in c plus plus

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.

0 0 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x