Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Destructors

A destructor  is a special member function used to finalize an object. The name the destructor for class T is T() and, like constructors, it has no return value. The destructor takes no arguments and, therefore, there is only one destructor per class.

It is normally not necessary to call a destructor explicitly. The destructor for an object is automatically invoked at the end of the lifetime of that object. In particular, this means that the destructors for global variables run after the main routine exits, and that the destructors for local and temporary variables run when the program exits the scope containing those variables.

If the programmer does not define a destructor explicitly, the C++ compiler generates one. The compiler-generated destructor simply invokes the destructors for the member variables of the class. The members of a class are always destroyed in the reverse of the order in which they were constructed.

Program gif defines explicitly a destructor for the class Complex (lines 17-18). In this case, the body of the destructor is empty. When the destructor runs, the body of the destructor is run first. After the body of the destructor has completed, the destructors for the member variables run (automatically).


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.