Declaring Destructors

Destructors are functions with the same name as the class but preceded by a tilde (~).

Syntax

~class-name()

or

class-name:: ~class-name()

The first form of the syntax is used for destructors declared or defined inside a class declaration; the second form is used for destructors defined outside a class declaration.

Several rules govern the declaration of destructors. Destructors:

Do not accept arguments.

Cannot specify any return type (including void).

Cannot return a value using the return statement.

Cannot be declared as const or volatile, nor can they be declared as static. However, they can be invoked for the destruction of objects declared as const, volatile, or static.

Can be declared as virtual. Using virtual destructors, you can destroy objects without knowing their type—the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes.