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

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

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