Destructors in C++

In a C++ Programming, Destructor is also a special member like constructor.

Like a constructor, destructor have the same name as their class , preceded by a tilde(~).

Destructor does not have a return type means it cant return any value.

Destructor destroys the class object created by constructor.

It is automatically called when object goes out of scope.

Destructor releases memory space occupied by objects.

In C++ Destructor is only one way to destroy the object .  

In C++ program we can define only one destructor. 

 Characteristics of Destructor:     

  • Destructor has a same name as the class in which it is resides, preceded by a tilde (~). 
  • Destructor is automatically called when object goes out of scope. 
  •  Destructor is only one way to destroy the object.
  • Destructor neither requires any argument nor returns any value. 
  •  It is not possible to define more than one destructor. 
  • Destructor cannot be overloaded.  

Example :


Note: In the above program, class “A” contains constructor and destructor.

When object obj is created , constructor is executed. When object goes out of scope, destructor   is executed.

Example: Write a C++  program to create an multiple object and releases them using destructor.