Destructor in C++ | C++ Tutorials
×

Destructor in C++

3069

We already learned about constructor in our previous Topic. The destructor is opposite of the constructor. It is used to free the object memory. It is automatically invoked as the object goes out of the scope.

Syntax of Destructor

class classname
{
public:
~ classname() // Destructor is defined
{
}
};


Features of Destructor
a) The name of the Destructor is also identical to the class name except that it starts with a tilde(~)
b) The destructor never returns type not even void.
c) The destructor is also a special member function as Constructor but it is used to destroy objects.

A simple program illustrating Constructor and Destructor in C++

#include <iostream>
using namespace std;

class coding{
public:
  // Constructor
  coding(){
    cout<<"Constructor Called"<<endl;
  }
  // Destructor

  ~coding(){
    cout<<"Destructor Called"<<endl;
   }

   void display(){
     cout<<"Welcome to Codingtag"<<endl;
   }
};

int main(){

   // Object created
   coding j;
   // Member function display is called

   j.display();
   return 0;
}

Output:
Constructor Called
Welcome to Codingtag
Destructor Called
Application of Destructor
Destructors are used to release the memory of the pointer variables, objects and in closing resources and the files.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments