Destructor: Destructor is a special class function which destroys the object as soon as the scope of an object ends. The destructor is called automatically by the compiler when the object goes out of scope. The syntax for destructor is same as that for the constructor, the class name is used for the name of the destructor, with a tilde ~ sign as a prefix to it.
A destructor function is called automatically when the object goes out of scope:
(1) When the function ends
(2) When the program ends
(3) When a block containing local variables ends
(4) When a delete operator is called
Important points on destructors:
- Destructors don’t take any argument and don’t return anything
- There can only be one destructor in a class with classname preceded by ~, no parameters and no return type.
- It is good to make destructors virtual in base class when we have a virtual function