O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required