This documentation is archived and is not being maintained.


"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:

// spec1_destructors.cpp
#include <string.h>

class String
    String( char *ch );  // Declare constructor
    ~String();           //  and destructor.
    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.
    // Deallocate the memory that was previously reserved
    //  for this string.
    delete[] _text;
int main()

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

See Also

Special Member Functions