|
|
|
|
|
|
|
The arrays discussed so far store all their members on the stack. Usually stack memory is severely limited, whereas free store memory is far larger. It is possible to declare each object on the free store and then to store only a pointer to the object in the array. This dramatically reduces the amount of stack memory used. Listing 15.4 rewrites the array from Listing 11.4, but it stores all the objects on the free store. As an indication of the greater memory that this makes possible, the array is expanded from 5 to 500, and the name is changed from Litter to Family. |
|
|
|
|
|
|
|
|
LISTING 15.4 STORING AN ARRAY ON THE FREE STORE |
|
|
|
 |
|
|
|
|
1: // Listing 15.4 - An array of pointers to objects
2:
3: #include <iostream.h>
4:
5: class CAT
6: {
7: public:
8: CAT() { itsAge = 1; itsWeight=5; } // default constructor
9: ~CAT() {} // destructor
10: int GetAge() const { return itsAge; }
11: int GetWeight() const { return itsWeight; }
12: void SetAge(int age) { itsAge = age; }
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: cout << Cat # << i+1 << : << Family[i]->GetAge() << endl;
33: return 0;
34: } |
|
|
|
|
|