C++

C++ Destructors – Detailed Coding Tips

Contrary to constructors, which are used to initialize an object, destructors are specific member functions that destroy (or delete) the object.

Syntax of Destructor

~class_name()    
{   
   //Some code   
}

Like the constructor, the name of the destructor must exactly match the class name. The grammar above illustrates how a destructor declaration must always start with the tilde() symbol.

The destructor is called when?

A destructor is automatically called when:
1) The program finished execution.
2) When a scope (the { } parenthesis) containing local variable ends.
3) When you call the delete operator.

Destructor Example

#include <iostream>
using namespace std;
class HelloWorld{
public:
  //Constructor
  HelloWorld(){
    cout<<"Constructor is called"<<endl;
  }
  //Destructor
  ~HelloWorld(){
    cout<<"Destructor is called"<<endl;
   }
   //Member function
   void display(){
     cout<<"Hello World!"<<endl;
   }
};
int main(){
   //Object created
   HelloWorld obj;
   //Member function called
   obj.display();
   return 0;
}

Output:

Constructor is called
Hello World!
Destructor is called

Destructor is king

1) The name should start with the tilde symbol (~) and match the class name.
2) A class may not have more than one destructor.
3) Destructors do not accept any parameters, in contrast to constructors, which may accept parameters.
4) Like constructors, they don’t have a return type.
5) The compiler creates a default destructor and inserts it into your code if you don’t specify one for a class.

Related Articles

Leave a Reply

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

Back to top button