Wednesday, November 21, 2007

Destructor in C++

A destructor is a class associate function that has the same name as the constructor (and the class) but with a ~ (tilde) in front. It is declared as like this in a program
~Circle() ;
When an object goes out of extent or more rarely is explicitly destroyed, its destructor is called. For example if the object has dynamic variables, like pointers then that require to be freed and the destructor is the proper place. Unlike constructors, the destructors can and should be made virtual if you have derived classes.

The use of the destructor is to release or relinquish all resources for example memory, close any open files etc when an object of this class is destroyed. Normally such resources will have been acquired by the class constructor.

No comments: