< previous page page_1034 next page >

Page 1034
Summary
Pointer types and reference types are simple data types for storing memory addresses. Variables of these types do not contain data; rather, they contain the addresses of other variables or data structures. Pointer variables require explicit dereferencing using the * operator. Reference variables are dereferenced implicitly and are commonly used to pass nonarray parameters by reference.
A powerful use of pointers is to create dynamic variables. The pointer is created at compile time, but the data to which the pointer points is created at run time. The built-in operator new creates a variable on the free store (heap) and returns a pointer to that variable. A dynamic variable is not given a name, but rather is accessed through a pointer variable.
The use of dynamic data saves memory space because a variable is created only when it is needed at run time. When a dynamic variable is no longer needed, it can be deallocated (using delete) and the memory space can be used again. The use of dynamic data can also save machine time when large structures are being sorted. The pointers to the large structures, rather than the large structures themselves, can be rearranged.
When C++ class objects point to data on the free store, it is important to distinguish between shallow and deep copy operations. A shallow copy of one class object to another copies only the pointers and results in two class objects pointing to the same dynamic variable. A deep copy results in two distinct copies of the pointed-to data. Therefore, classes that manipulate dynamic data usually require a complete collection of support routines: one or more constructors, a destructor (for cleaning up the free store), a deep copy operation, and a copy-constructor (for deep copying during initialization of one class object by another).
Quick Check
1. How would you declare each of the following pointer variables? (pp. 968979)
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
a. A variable intPtr that can point to a single int variable.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
b. A variable arrPtr that can point to a float array.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
c. A variable recPtr that can point to a structure of the following type.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
struct RecType
{
    int   age;
    float height;
    float weight;
};
2. Given the declarations

 
< previous page page_1034 next page >