Declaring Arrays on the Heap

It is possible to put the entire array on the heap, 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 heap 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 to—or has the address of—Family[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's SetAge() function is called with the value 10. The pointer is then incremented to point to the next CAT, and the second CAT's SetAge() method is then called.

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

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