Destructors in C++ C-PLUS-PLUS

Destructors in C++  

Destructors in C++

Destructors in C++

Destructor is a member function that destructs or deletes an object.

When is the destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called 

There can only one destructor in a class with class name preceded by ~, no parameters, and no return type.


How destructors are different from a normal member function?
Destructors have the same name as the class preceded by a tilde (~). Destructors don’t take any argument and don’t return anything

Example

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

Output:

Constructor is called
Hello World!
Destructor is called

Destructor rules

1) The name should begin with a tilde sign(~) and must match the class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, the compiler generates a default destructor and inserts it into your code.

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries