1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn about C++ Classes and Objects

By , About.com Guide

9 of 9

Tidying Up - C++ Destructors

A destructor is a class member function that has the same name as the constructor (and the class ) but with a ~ (tilde) in front.

~Circle() ;
When an object goes out of scope or more rarely is explicitly destroyed, its destructor is called. For instance if the object has dynamic variables, such as pointers then those need to be freed and the destructor is the appropriate place.

Unlike constructors, destructors can and should be made virtual if you have derived classes. In the Point and Circle classes example the destructor is not needed as there is no clean up work to be done, it just serves as an example. Had there been dynamic member variables (e.g. pointer) then those would have required freeing to prevent memory leaks.

Also when the derived class adds members that require tidying up, virtual destructors are needed. When virtual, the most derived classe destructor is called first, then its immediate ancestor's destructor is called, and so on up to the base class.

In our example,

~Circle() ;
then
~Point() ;
The base classes destructor is called last.

This completes this lesson. In the next lesson, learn about default constructors, copy constructors and assignment.

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Tidying Up - C++ Destructors

©2009 About.com, a part of The New York Times Company.

All rights reserved.