Just as the malloc function has the free function as its counterpart, the new operator has the delete operator as its counterpart. The delete operator deallocates blocks of memory, returning them to the free store for subsequent allocations.
The syntax for delete is simple:
Date *firstPtr;
int i;
firstPtr = new Date( 3, 15, 1985 ); // Constructor called
i = firstPtr->getMonth(); // Returns 3
delete firstPtr; // Destructor called, memory freed
The delete operator automatically calls the destructor for the object before it deallocates the memory. Since the Date class's destructor doesn't do anything, this feature is not demonstrated in this example.
You can only apply delete to pointers that were returned by new, and you can only delete them once. Deleting a pointer not obtained from new or deleting a pointer twice will cause your program to behave strangely, and possibly to crash. It is your responsibility to guard against these errors; the compiler cannot detect them. You can, however, delete a null pointer (a pointer with value 0) without any adverse effects.