What is Destructor In C++

Share Your Love

A destructor is the complete opposite of a constructor, it destroys class objects. It can only be specified once per class. It is called automatically, just like Constructors.

A Constructor is what a destructor is. It has to be named after the class. It is, however, preceded with a tilde symbol (~).

Destructors in C++ are not allowed to contain arguments. Modifiers can’t be used on destructors, either.

#Note

C++ Constructor and Destructor Example:

Let’s look at an example of a C++ constructor and destructor that is automatically invoked:

#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

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter