C++ Destructor


It is a special member function of the class and executed whenever an object of the class goes out to scope.

 

Destructor has the exact same name as the class it belongs except that the first character of the name must be tilde (~). It is very useful for releasing space on the heap. It works exactly opposite to the constructor. Same as the constructor, destructors do not have a return value.

 

The destructor does not take any argument as well as can't be overloaded. It also destructs the objects of the classes. It can define only one time in class. The destructor is defined as like a constructor. As same as a constructor, it is invoked automatically.


Syntax:

~class_name()

Example:

#include  <iostream> 
using namespace std; 
 
class circle  
{  
   public:  
    int area,circum; 
    int radius=8; 
    circle() 
    {  
        area = 3.14 * radius * radius;  
        cout << "Constructor Invoked" << endl;
    }  
    ~circle() // destructor  
    {  
        circum = 3.14 * 2 * radius; 
        cout << "Destructor Invoked" << endl;
        cout << "Area of Circumference: "<< circum << endl;  
    }  
};  
int main()  
{  
    circle c;            
    cout << "Area of Circle: " << c.area << endl;
    return 0;  
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.