Sams Teach Yourself C++ in 21 Days

(singke) #1
13:
14: private:
15: int itsAge;
16: int itsWeight;
17: };
18:
19: int main()
20: {
21: Cat * Family[500];
22: int i;
23: Cat * pCat;
24: for (i = 0; i < 500; i++)
25: {
26: pCat = new Cat;
27: pCat->SetAge(2*i +1);
28: Family[i] = pCat;
29: }
30:
31: for (i = 0; i < 500; i++)
32: {
33: cout << “Cat #” << i+1 << “: “;
34: cout << Family[i]->GetAge() << endl;
35: }
36: return 0;
37: }

Cat #1: 1
Cat #2: 3
Cat #3: 5
...
Cat #499: 997
Cat #500: 999
The Catobject declared on lines 5–17 is identical to the Catobject declared in
Listing 13.4. This time, however, the array declared on line 21 is named Family,
and it is declared to hold 500 elements. More importantly, these 500 elements are point-
ers to Catobjects.
In the initial loop (lines 24–29), 500 new Catobjects are created on the free store, and
each one has its age set to twice the index plus one. Therefore, the first Catis set to 1,
the second Catto 3, the third Catto 5, and so on. After the pointer is created, line 28
assigns the pointer to the array. Because the array has been declared to hold pointers, the
pointer—rather than the dereferenced value in the pointer—is added to the array.
The second loop in lines 31–35 prints each of the values. On line 33, a number is printed
to show which object is being printed. Because index offsets start at zero, line 33 adds 1

OUTPUT


422 Day 13


LISTING13.6 continued

ANALYSIS
Free download pdf