CLASS DESTRUCTORS

Although this section heading relates to destructors, it’s also about dynamic memory allocation. When you allocate memory in the free store for class members, you are invariably obliged to make use of a destructor, in addition to a constructor, of course. As you’ll see, dynamically allocating memory for class members will also require you to write a copy constructor.

What Is a Destructor?

A destructor is a function that destroys objects when they are no longer required or when they go out of scope. The class destructor is called automatically when an object goes out of scope. Destroying an object involves freeing the memory occupied by the data members of the object (except for static members, which continue to exist even when there are no class objects in existence). The class destructor is a member function with a name that is a tilde (~) followed by the class name. A destructor doesn’t return a value and doesn’t have parameters. For example, the prototype for the CBox class destructor is:

~CBox();                 // Class destructor prototype

Because a destructor has a specific name and no parameters, there can only ever be one destructor in a class.

NOTE It’s an error to specify a return value or parameters for a destructor.

The Default Destructor

All the objects that you have been using up to now have been destroyed automatically by the default destructor for the class. The default destructor is always generated automatically by the compiler if you do not define your ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.