|

Family
is a pointer, a pointer to the array on the free
store. When, on line 33, the pointer pCat is dereferenced,
the CAT object itself is stored in the array (why
not? the array is on the free store). But pCat is
used again in the next iteration of the loop. Isn’t
there a danger that there will now be no pointer
to that CAT object, and a memory leak has been created?
This
would be a big problem, except that deleting Family
returns all the memory set aside for the array.
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 in lines 26, 29, and 37. Then uncomment the
cout statement in line 21. When line 40 is reached
and the array is destroyed, each CAT object 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 <class>[size], you delete that array and
free all its memory with delete[]. The brackets
signal the compiler that this array is being deleted.
If
you leave the brackets off, only the first object
in the array will be deleted. You can prove this
to yourself by removing the bracket on line 40.
If you edited line 21 so that the destructor prints,
you should now see only one CAT object destroyed.
Congratulations! You just created a memory leak.
DO
remember that an array of n items is numbered from
zero through n-1. DON’T write or read past
the end of an array. DON’T confuse an array
of pointers with a pointer to an array. DO use
array indexing with pointers that point to arrays.
|