WHAT YOU WILL LEARN IN THIS CHAPTER:
What a class destructor is and when and why it is 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
What a union is and how it can be used
How to make objects of your class work with C++ operators such as
How to use rvalue reference parameters to avoid unnecessary copying of class objects
What class templates are and how to define and use them
How to use the standard
string class for string operations in native C++ programs
How to overload operators in C++/CLI 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++.
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 will also require you to write your own copy constructor.
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 ...