Arrays of Pointers

The arrays discussed so far store all their members on the stack. Usually stack memory is severely limited, whereas heap memory is far larger. It is possible to declare each object on the heap 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 heap. 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 Heap
 0:  // Listing 15.4 - An array of pointers to objects
 1:  #include <iostream>
 2:
 3:  class CAT
 4:  {
 5:  public:
 6:      CAT() { itsAge = 1; itsWeight=5; }  // default constructor
 7:      ~CAT() {}                           // destructor
 8:      int GetAge() const { return itsAge; }
 9:      int GetWeight() const { return itsWeight; }
10:      void SetAge(int age) { itsAge = age; }
11:
12:  private:
13:      int itsAge;
14:      int itsWeight;
15:  };
16:
17:  int main()
18:  {
19:      CAT * Family[500];
20:      int i;
21:      CAT * pCat;
22:      for (i = 0; i < 500; i++)
23:      {
24:          pCat = new CAT;
25:          pCat->SetAge(2*i +1);
26:          Family[i] = pCat;
27:      }
28:
29:      for (i = 0; i < 500; i++)
30:          std::cout << "Cat #" << i+1 << ": "
31:              << Family[i]->GetAge() << std::endl;
32:
33:      for (i = 0; i < 500; i++)
34:      {
35:          delete Family[i];
36:          Family[i] = NULL;
37:      }
38:
39:      return 0;
40:  }


Cat #1: 1
Cat #2: 3
Cat #3: 5
...
Cat #499: 997
Cat #500: 999
					

The CAT object declared in lines 3–15 is identical to the CAT object declared in Listing 15.3. This time, however, the array declared in line 19 is named Family, and it is declared to hold 500 pointers to CAT objects.


In the initial loop (lines 22–27), 500 new CAT objects are created on the heap, 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 pointer—rather than the dereferenced value in the pointer—is added to the array.

The second loop (lines 29–31) 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 heap.

The third loop deletes the CATs from the heap and sets all elements of Family to null.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.38.41