Destructors

A destructor is a member function with the same name as its class prefixed by a ~ (tilde).

For example:

class X
{
public:
      X();       // constructor for class X
      ~X();      // destructor for class X
};

A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const, volatile, or static. A destructor can be declared virtual or pure virtual. A union cannot have as a member an object of a class with a destructor.

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

Class members that are class types can have their own destructors. Both base and derived classes can have destructors, although destructors are not inherited. If a base class or a member of a base class has a destructor and a class derived from that base class does not declare a destructor, a default destructor is generated. The default destructor calls the destructors of the base class and members of the derived class. Default destructors are generated with default public access.

Destructors are called in the reverse order to constructors:

  1. destructor for a class object is called before destructors for members and bases are called.
  2. for nonstatic members are called before destructors for base classes are called.
  3. for nonvirtual base classes are called before destructors for virtual base classes are called.

 

When an exception is thrown for a class object with a destructor, the destructor for the temporary object thrown is not called until control passes out of the catch block. For more information, see Constructors and Destructors in Exception Handling.

Destructors are implicitly called when an automatic or temporary object passes out of scope. They are implicitly called at program termination for constructed external and static objects. Destructors are invoked when you use the delete operator for objects created with the new operator.

You can use a destructor explicitly to destroy objects, although this practice is not recommended. If an object has been placed at a specific address by the new operator, you can call the destructor of the object explicitly to destroy it. An explicitly called destructor cannot delete storage.

Note: You can only call destructors for class types. You cannot call destructors for simple types. The call to the destructor in the following example causes the compiler to issue a warning:

      int * ptr;
      ptr -> int::~int(); // warning


Constructors and Destructors Overview


Constructors
Virtual Functions
Constructors and Destructors in Exception Handling
new Operator
delete Operator


Example of Destructors