Deleting Arrays on the Heap

Family is a pointer—a pointer to the new CAT array on the heap. 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 heap.) But pCat is used again in the next iteration of the loop. Isn't there a danger that there is now no pointer to that CAT object, and a memory leak is 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 heap.

To see this, change the size of the array from 500 to 10 in lines 24, 27, and 35. Then uncomment the cout statement in line 19. When line 39 is reached and the ...

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.