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

Don't Return a Reference to an Object That Isn't in Scope!

After C++ programmers learn to pass by reference, they have a tendency to go hog-wild. It is possible, however, to overdo it. Remember that a reference is always an alias that refers to some other object. If you pass a reference into or out of a function, be sure to ask yourself, “What is the object I'm aliasing, and will it still exist every time it's used?”

Listing 12.4 illustrates the danger of returning a reference to an object that no longer exists.

Listing 12.4. Returning a Reference to a Nonexistent Object
 0: // Listing 12.4 1: // Returning a reference to an object 2: // which no longer exists 3: #include <iostream> 4: 5: class SimpleCat 6: { 7: public: 8: SimpleCat (int age, ...

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