zondag 1 juli 2007

Destructors

When you use a constructor to create an object, the program undertakes the responsibolity of tracking that object until it expires. At that time, the program automatically calls a special member function bearing the formidable title destructor The destructor should clean up any debris, so it actually serves a useful purpose. For example, if your constructor uses new to allocate memory, the destructor should use delete to free that memory.
In case of the Stock class, the Stock constructor doesn't do anything fancy like using new, so the Stock class destructor doesn't really have any tasks to perform. In such a case, you can simply let the compiler generate an implicit, do-nothing destructor, which is exactly what the first version of the Stock class does.

Like a constructor, a destructor has a special name: It is formed from the class name preceded by a tilde(~). Thus the destructor for the Stock class is called ~Stock. Also, like a constructor, a destructor can have no return value and has no declared type. Unlike a constructor, a destructor must have no arguments. Thus the prototype for a Stock destructor must be this:

~Stock();

Because a Stock destructor has no vital duties, you can code it as a do-nothing function:

Stock::~Stock()
{
}

However, just so that you can see when the destructor is called, you can code it this way:

Stock::~Stock() // class destructor
{
cout << "Bey, " << company << "!\n";
}

When should a destructor be called? The compiler handles this decision; normally your code shouldn't explicitly call a destructor.
If you create a static storage class object, its destructor is called automatically when the program terminates. If you create an automatic storage class object, as the examples have been doing, its destructor is called automatically when the program exits the block of code in which the object is defined.
If the object is created using new, it resides in heap memory, or the free store, and its destructor is called automatically when you use delete to free the memory.
Finally, a program can create temporary objects to carry out certain operations; in that case, the program automatically calls the destructor for the object when it has finished using it.

Because a destructor is called automatically when a class object expires, there ought to be a destructor. If you don't provide one, the compiler implicitely declares a default constructor and, if it detects code that leads to the destruction of an object, it provides a definition for the destructor.

Geen opmerkingen: