|
|
|
|
|
|
|
Cat #1: 1
Cat #2: 3
Cat #3: 5
Cat #499: 997
Cat #500: 999 |
|
|
|
|
|
|
|
|
Analysis: The CAT object declared in lines 517 is identical to the CAT object declared in Listing 15.3. This time, however, the array declared in line 21 is named Family, and it is declared to hold 500 pointers to CAT objects. |
|
|
|
|
|
|
|
|
In the initial loop (lines 2429), 500 new CAT objects are created on the free store, and each one has its age set to twice the index plus one. Therefore, the first CAT is set to 1, the second CAT to 3, the third CAT to 5, and so on. Finally, the pointer is added to the array. |
|
|
|
|
|
|
|
|
Because the array has been declared to hold pointers, the pointerrather than the dereferenced value in the pointeris added to the array. |
|
|
|
|
|
|
|
|
The second loop (lines 31 and 32) prints each of the values. The pointer is accessed by using the index, Family[i]. That address is then used to access the GetAge() method. |
|
|
|
|
|
|
|
|
In this example, the array Family and all its pointers are stored on the stack, but the 500 CATs that are created are stored on the free store. |
|
|
|
|
|
|
|
|
Declaring Arrays on the Free Store |
|
|
|
|
|
|
|
|
It is possible to put the entire array on the free store, also known as the heap. You do this by calling new and using the subscript operator. The result is a pointer to an area on the free store that holds the array. For example: |
|
|
|
|
|
|
|
|
CAT *Family = new CAT[500]; |
|
|
|
|
|
|
|
|
declares Family to be a pointer to the first in an array of 500 CATs. In other words, Family points toor has the address ofFamily[0]. |
|
|
|
|
|
|
|
|
The advantage of using Family in this way is that you can use pointer arithmetic to access each member of Family. For example, you can write |
|
|
|
|
|
|
|
|
CAT *Family = new CAT[500];
CAT *pCat = Family; // pCat points to Family[0]
pCat->SetAge(10); // set Family[0] to 10
pCat++; // advance to Family[1]
pCat->SetAge(20); // set Family[1] to 20 |
|
|
|
|
|
|
|
|
This declares a new array of 500 CATs and a pointer to point to the start of the array. Using that pointer, the first CAT'sSetAge() function is called with the value 10. The |
|
|
|
|
|