Managing Arrays and Strings 429
13
the Familyarray as an array name. The one thing you will need to do, however, is to free
the memory you allocated in setting up the array. This is done on line 39 with a call to
delete.
Deleting Arrays on the Free Store ..................................................................
What happens to the memory allocated for these Catobjects when the array is
destroyed? Is there a chance of a memory leak?
Deleting Familyautomatically returns all the memory set aside for the array if you use
the deletewith the []operator. By including the square brackets, the compiler is smart
enough to destroy each object in the array and to return its memory to the free store.
To see this, change the size of the array from 500 to 10 on lines 25, 28, and 33. Then
uncomment the coutstatement on line 20. When line 39 is reached and the array is
destroyed, each Catobject destructor is called.
When you create an item on the heap by using new, you always delete that item and free
its memory with delete. Similarly, when you create an array by using new
ets signal the compiler that this array is being deleted.
If you leave the brackets off, only the first object in the array is deleted. You can prove
this to yourself by removing the bracket on line 39. If you edited line 20 so that the
destructor prints, you should now see only one Catobject destroyed. Congratulations!
You just created a memory leak.
Resizing Arrays at Runtime............................................................................
The biggest advantage of being able to allocate arrays on the heap is that you determine
the size of the array at runtime and then allocate it. For instance, if you asked the user to
enter the size of a family into a variable called SizeOfFamily, you could then declare a
Catarray as follows:
Cat *pFamily = new Cat[SizeOfFamily];
With that, you now have a pointer to an array of Catobjects. You can then create a
pointer to the first element and loop through this array using a pointer and pointer
arithmetic:
Cat *pCurrentCat = Family[0];
for ( int Index = 0; Index < SizeOfFamily; Index++, pCurrentCat++ )
{
pCurrentCat->SetAge(Index);
};