Destructor

The destructor in a class is a special member function which takes care of cleaning up the contents of the object when it goes out of scope.

  • There can only be one destructor function per class.
  • The name of the destructor is the name of the class itself preceded with a tilde (~). It takes no arguments and does not have a return type.
  • The destructor is automatically called when an object goes out of scope.

A destructor is needed if the class holds or uses any resources which must be released when the object is destroyed, such as file handles or pointers to allocated memory. In a simple class which¬†does not hold any resources then a destructor is not necessary since C++ will automatically clean up the memory that the object used. You also don’t need to write a destructor if the class holds resources through smart pointers (like unique_ptr) or standard library containers¬†like std::vector as these will automatically delete themselves when they go out of scope. Notice that if you need to write a constructor in a class and intend to later on inherit from the class that you are writing now then you must make the destructor virtual (see the post on virtual destructor).

Example of a class where a destructor is necessary:

Example of a class using string from the standard library which makes it possible to avoid writing a destructor:

The destructor is an important piece in the automatic cleaning up of resources necessary for RAII.

Facebookgoogle_pluslinkedinmail