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 ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.