Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Pointers 243

8


The destructor (lines 28–32) cleans up the allocated memory. Because this is the destruc-
tor, there is no point in assigning these pointers to null because they will no longer be
accessible. This is one of the safe places to break the rule that deleted pointers should be
assigned to null, although following the rule doesn’t hurt.
The calling function (in this case,main()) is unaware that itsAgeand itsWeightare
pointers to memory on the free store. main()continues to call GetAge()and SetAge(),
and the details of the memory management are hidden in the implementation of the
class—as they should be.
When Friskyis deleted on line 41, its destructor is called. The destructor deletes each of
its member pointers. If these, in turn, point to objects of other user-defined classes, their
destructors are called as well.

Understanding What You Are Accomplishing
The use of pointers as was done in Listing 8.7 would be pretty silly in a real program
unless a good reason existed for the Catobject to hold its members by reference. In this
case, there is no good reason to use pointers to access itsAgeand itsWeight, but in
other cases, this can make a lot of sense.
This brings up the obvious question: What are you trying to accomplish by using pointers
as references to variables instead of just using variables? Understand, too, that you must
start with design. If what you’ve designed is an object that refers to another object, but
the second object might come into existence before the first object and continue after
the first object is gone, then the first object must contain the second by reference.
For example, the first object might be a window and the second object might be a docu-
ment. The window needs access to the document, but it doesn’t control the lifetime of
the document. Thus, the window needs to hold the document by reference.
This is implemented in C++ by using pointers or references. References are covered on
Day 9, “Exploiting References.”

The thisPointer ..................................................................................................


Everyclassmember function has a hidden parameter: the thispointer. thispoints to
“this” individual object. Therefore, in each call to GetAge()or SetAge(), each function
gets thisfor its object as a hidden parameter.
It is possible to use the pointer to thisexplicitly, as Listing 8.8 illustrates.
Free download pdf