Sams Teach Yourself C++ in 21 Days

(singke) #1
11: void SetAge(int age) { itsAge = age; }
12:
13: private:
14: int itsAge;
15: int itsWeight;
16: };
17:
18: Cat :: ~Cat()
19: {
20: // std::cout << “Destructor called!\n”;
21: }
22:
23: int main()
24: {
25: Cat * Family = new Cat[500];
26: int i;
27:
28: for (i = 0; i < 500; i++)
29: {
30: Family[i].SetAge(2*i +1);
31: }
32:
33: for (i = 0; i < 500; i++)
34: {
35: std::cout << “Cat #” << i+1 << “: “;
36: std::cout << Family[i].GetAge() << std::endl;
37: }
38:
39: delete [] Family;
40:
41: return 0;
42: }

Cat #1: 1
Cat #2: 3
Cat #3: 5
...
Cat #499: 997
Cat #500: 999
Line 25 declares Family, which is a pointer to an array of 500 Catobjects. The
entire array is created on the free store with the call to new Cat[500].
On line 30, you can see that the pointer you declared can be used with the index operator
[], and thus be treated just like a regular array. On line 36, you see that it is once again
used to call the GetAge()method. For all practical purposes, you can treat this pointer to

OUTPUT


428 Day 13


LISTING13.8 continued

ANALYSIS
Free download pdf