Chapter 8. More on Classes

In this chapter, you will extend your knowledge of classes by understanding how you can make your class objects work more like the basic types in C++. You will learn about:

  • Class destructors and when and why they are necessary

  • How to implement a class destructor

  • How to allocate data members of a native C++ class in the free store and how to delete them when they are no longer required

  • When you must write a copy constructor for a class

  • Unions and how they can be used

  • How to make objects of your class work with C++ operators such as + or *

  • Class templates and how you define and use them

  • How to overload operators in C++/CLI classes

Class Destructors

Although this section heading refers 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, and, as you'll see later in this chapter, using dynamically allocated class members also require you to write your own copy constructor.

What Is a Destructor?

A destructor is a function that destroys an object when it is no longer required or when it goes 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 destructor for a class is a member ...

Get Ivor Horton's Beginning Visual C++® 2005 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.