-->

What are destructors?

Destructors are complements of constructors. When an object is destroyed, its destructor is automatically called. Destructors are mainly useful for doing the clean up job. E.g. an object may have allocated some memory during its lifetime; destructors are the place where this memory is deallocated. Or an object may need to close some files by releasing its handles which it had previously obtained.


- Destructor function has same name as that of a constructor; but the name is preceded by a tilde (‘~’) sign.

- We will expand the above example of a stack class to include a destructor:


The output of the program would be :
- As seen from the o/p the constructors and destructors are automatically called. What is a destructor? A destructor is used to destroy the objects created that have been created by a constructor. It has a same name as its class, just that it is preceded by a tidle.

Explain constructors and destructors.

- Constructors are the member functions of the class that executes automatically whenever an object is created. Constructors have the same name as the class. Constructors initialize the class. Constructors can’t have return type. Destructors are called when the objects are destroyed.

- Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor takes no arguments and has no return type.

What are destructors?

- Destructors are called automatically to destroy the object. There's only one destructor for each object. The name of the destructor is the name of the class, preceeded by a tilde (~).

- Example :