Destructors

“Destructor” functions are the inverse of constructor functions. They are called when objects are destroyed (deallocated). Designate a function as a class’s destructor by preceding the class name with a tilde (~). For example, the destructor for class String is declared: ~String().

The destructor is commonly used to “clean up” when an object is no longer necessary. Consider the following declaration of a String class:

#include <string.h>

class String
{
public:
    String( char *ch );  // Declare constructor
    ~String();           //  and destructor.
private:
    char *_text;
};

// Define the constructor.
String::String( char *ch )
{
    // Dynamically allocate the correct amount of memory.
    _text = new char[strlen( ch ) + 1];

    // If the allocation succeeds, copy the initialization string.
    if( _text )
       strcpy( _text, ch );
}

// Define the destructor.
String::~String()
{
    // Deallocate the memory that was previously reserved
    //  for this string.
    delete[] _text;
}

In the preceding example, the destructor String::~String uses the delete operator to deallocate the space dynamically allocated for text storage.