Articles

What is destructor in C++ with example?

What is destructor in C++ with example?


In this C++ interview questions, we will learn about:

  • what is destructor in c++?
  • properties of destructor in c++
  • example of destructor in c++

What is Destructor in C++?

Destructor in c++ is a member function that works opposite to constructor (it deletes the objects of classes).

 

Syntax of destructor

~name_of_constructor()  //tilde sign(~)

Properties of Destructor in C++

  • Like a constructor, it is invoked automatically.
  • It must have the same name as the class name.
  • The destructor doesn't declare as static and has no argument.
  • It has no return type, as well as destructor address, can't be accessed.

Note

There is only one destructor in a class with class name preceded by ~

Example of Destructor in C++

A simple example of destructor in c++ is given below:

#include <iostream>  
using namespace std;  

class TIH  
 {  
   public:  
        TIH()    
        {    
            cout<<"Constructor is here"<<endl;    
        }    
        ~TIH()    // defination of destructor
        {    
            cout<<"Destructor is present"<<endl;    
        }  
};  

int main()   
{  
    TIH t1; //creating an object of TIH 
    TIH t2; 
    return 0;  
}  

OUTPUT

Constructor is here

Constructor is here

Destructor is present

Destructor is present


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Feb 14,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!