Destructors in C++

A destructor in C++, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor in C++ is a member function whose name is the same as the class name but is preceded by a tilde (~). For example, the destructor for the class integer can be defined as shown below:

~integer()
     {

     }

A destructor in C++ never takes any arguments nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or the block or the function as the case may be) to clean up the storage that is no longer accessible. It is a good practice to declare destructors in a program since it releases memory space for future use.

Whenever new is used to allocate memory in the constructors, we should use delete to free that memory.

Note: new and delete operators would be discussed later.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: