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

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.