Returning a Reference to an Object on the Heap

You might be tempted to solve the problem in Listing 12.4 by having TheFunction() create Frisky on the heap. That way, when you return from TheFunction(), Frisky will still exist.

The problem with this approach is: What do you do with the memory allocated for Frisky when you are done with it? Listing 12.5 illustrates this problem.

Listing 12.5. Memory Leaks
 0: // Listing 12.5 1: // Resolving memory leaks 2: #include <iostream> 3: 4: class SimpleCat 5: { 6: public: 7: SimpleCat (int age, int weight); 8: ~SimpleCat() {} 9: int GetAge() { return itsAge; } 10: int GetWeight() { return itsWeight; } 11: 12: private: 13: int itsAge; 14: int itsWeight; 15: }; 16: 17: SimpleCat::SimpleCat(int age, int weight): ...

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.