Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Pointers 245

8


theRect is 10 feet long.
theRect is 5 feet wide.
theRect is 20 feet long.
theRect is 10 feet wide.
The SetLength()accessor function on lines 11–12 and the GetLength()acces-
sor function on lines 13–14, both explicitly use the thispointer to access the
member variables of the Rectangleobject. The SetWidth()and GetWidth()accessors
on lines 16–19 do not. No difference exists in their behavior, although the syntax is eas-
ier to understand.
If that were all there was to this, there would be little point in bothering you with it.
this, however, is a pointer; it stores the memory address of an object. As such, it can be
a powerful tool.
You’ll see a practical use for thison Day 10, “Working with Advanced Functions,”
when operator overloading is discussed. For now, your goal is to know about thisand to
understand what it is: a pointer to the object that holds the function.
You don’t have to worry about creating or deleting the thispointer. The compiler takes
care of that.

Stray, Wild, or Dangling Pointers ........................................................................


Yet again, issues with pointers are being brought up. This is because errors you create in
your programs with pointers can be among the most difficult to find and among the most
problematic. One source of bugs that are especially nasty and difficult to find in C++ is
stray pointers. A stray pointer (also called a wild or dangling pointer) is created when
you call deleteon a pointer—thereby freeing the memory that it points to—and then
you don’t set it to null. If you then try to use that pointer again without reassigning it, the
result is unpredictable and, if you are lucky, your program will crash.
It is as though the Acme Mail Order company moved away, but you still pressed the pro-
grammed button on your phone. It is possible that nothing terrible happens—a telephone
rings in a deserted warehouse. On the other hand, perhaps the telephone number has
been reassigned to a munitions factory, and your call detonates an explosive and blows
up your whole city!
In short, be careful not to use a pointer after you have called deleteon it. The pointer
still points to the old area of memory, but the compiler is free to put other data there;
using the pointer without reallocating new memory for it can cause your program to
crash. Worse, your program might proceed merrily on its way and crash several minutes
later. This is called a time bomb, and it is no fun. To be safe, after you delete a pointer,
set it to null ( 0 ). This disarms the pointer.

OUTPUT


ANALYSIS
Free download pdf