I am currently reading the learn C++ in 21 days tutorial. In a chapter on references, when the author summarizes some of the main points inside a respective section, he explicitly states, "DON'T return a reference to a local object. "

I am simply curious what this means. I have an idea, but I don't understand why I can't do it, unless, of course, the memory would be reassigned when the variable goes out of scope.

Because a local object will destruct at the end of the code block / function and therefore you will be returning an invalid reference.

Awesome. Thank you for the help. I've also got one other question, this time about constructors.

In the following code,

1:     // Listing 9.13
2:      // Returning a reference to an object
3:      // which no longer exists
4:
5:      #include <iostream.h>
6:
7:      class SimpleCat
8:      {
9:      public:
10:            SimpleCat (int age, int weight);
11:            ~SimpleCat() {}
12:            int GetAge() { return itsAge; }
13:            int GetWeight() { return itsWeight; }
14:      private:
15:           int itsAge;
16:           int itsWeight;
17:      };
18:
19:      SimpleCat::SimpleCat(int age, int weight):
20:      itsAge(age), itsWeight(weight) {}
21:
22:      SimpleCat &TheFunction();
23:
24:      int main()
25:      {
26:           SimpleCat &rCat = TheFunction();
27:           int age = rCat.GetAge();
28:           cout << "rCat is " << age << " years old!\n";
29:     return 0;
30:      }
31:
32:      SimpleCat &TheFunction()
33:      {
34:           SimpleCat Frisky(5,9);
35:           return Frisky;
36: }
Output: Compile error: Attempting to return a reference to a local object!

What in the world does line 20 do?

What in the world does line 20 do?

19: SimpleCat::SimpleCat(int age, int weight):
20: itsAge(age), itsWeight(weight)
{}

The bolded part denotes an initialization done during the Constructor call. itsAge is set to age and itsWeight is set to weight when the constructor is called (sort-of like a pre-initialization). I suppose it reduces code-clutter in the Constructor, but I'm sure there's more to it than that.

SimpleCat :: SimpleCat(int age, int weight):

itsAge(age), itsWeight(weight) {}

It is defining Simple Cat's 2 parameter constructor. It is setting the age and weight. This is the more efficent method because if you define
itsAge = age;
itsWeight = weight; in the body of the construtor, you are basically calling the copy constructor on both the arguments and then assigning the values, which takes extra time.

Simply put, it is for initialization.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.