destructor in c++ | How to call destructor C++

The destructor  is a special member function whose name is same as the class name, but it is preceded by a tiled symbol(~).

For Example :-. 

the destructor for the class Example will bear the name  ~Example().

Definition of Destructor in C++ :-

A destructor is a member function and can be defined like any other member function. However, it doesn’t take any argument neither does it return any value.

Destructor destroys class objects created by constructor.

Note :-

Generally, A destructor should be defined under the public section of a class and it object can be destroyed in any function.

“dtor” is typical abbreviation for destructors.


following code piece outlines it

class Demo  {  int i, int j;
~Demo(){cout << "Destructing \n";}  // private destructor .
public :
 Demo(){i=0;j=0;}  // constructor
 void memb1(void);
 void memb2(void);
	
};
void Demo :: memb1(void)
{
	Demo s1 ; /* valid. object can be used here.it is a member functon 
	and  thus has an access to its private destructor */ 
}
void Demo :: memb2(void)
{
	Demo  s2 ; 
}
void abc (void)
{
	Demo s3; /*  valid.abc is a friend function and 
	thus has an access to sample's private members.*/
}

int main()
{
	Demo s4; /* invalid main() is a nonmember function and thus cannot access  
private members (destructor also as it is private). */
}

Some Characteristics of Destructors

The destructors have some special characteristics associated. These are : 

  1. A destructor is automatically executed when object goes out of the scope.
  2. A destructor does not have return type and not even void.
  3. Destructor can be virtual, but constructors can not .
  4. Only one destructor can be defined in  a class.
  5. The destructor does not have any  arguments.
  6. An object of a class with a destructor cannot be a member of a union.
  7. A destructor may not be static.
  8. They cannot be inherited.
  9. Not possible to take the address of a destructor.
  10. Member function may be called from within a destructor.
  11. Destructors can’t be overloaded.