8.6. Constructors and Destructors

A constructor is a method that is automatically run when a new instance of a class is made. A destructor is a method that is automatically run when the instance is destroyed. Constructors are called for all parent (base) classes of an instance starting with the root of the instance's class hierarchy. Destructors are called for all parent (base) classes of an instance starting with the class of the instance and proceeding toward the root of the instance's class hierarchy.

In Gamma these two methods take the special names constructor and destructor.

method Book.constructor ()
{
    total_books++;
}

method Book.destructor ()
{
    total_books [minus ][minus ];
}
	  

We'll now set the example variable total_books to 2 (since two have already been created: math and history):

Gamma> total_books = 2;
2
	

A new Catalog object can now be created, and the effect of the constructor and destructor observed:

Gamma> biology = new(Book);
{Book (data) (size . 0) (start_date)}
Gamma> total_books;
3
Gamma> biology = nil;
nil;
Gamma> total_books;
3
Gamma> gc();
166
Gamma> total_books;
2
	  

The constructor worked as expected, but the destructor appears to have failed. Only after the gc function was called did the destructor get called. The gc function forces the garbage collector to run. When biology was set to nil the memory containing the previous definition for biology was left unlinked. Once this unlinked memory was recovered by the garbage collector, the destructor was called.

The frequency of the garbage collector running will depend on the program written in Gamma. The garbage collector can be forced to run by using the gc function. Occasionally, system activity may prevent it from running immediately, but the requirement to run is noted and it will do so at the next opportunity.

Classes are often used to keep track of real-world objects, and as such, it is important to keep statistics on these objects. One of the most common methods of doing this is by using constructors and destructors to increment and decrement a counter of the number of objects created or currently available.