CS 70

References Exercise 3: References to References?

  • LHS Cow speaking

    You may be wondering whether you can have a reference to a reference.

  • Dog speaking

    That is exactly what I was wondering!

  • LHS Cow speaking

    Well, using what we know about references so far, see if you can guess what happens in this example.

Consider the following code snippet:

int m = 7;
int& n = m;
int& o = n;
o = 3;
cout << m << " " << n << " " << o;

Remember, a reference is just another name for its referent.

Okay, now don't worry about right or wrong, just give it some thought!

Draw a memory diagram of this snippet and then give the printed output:

  • RHS Cow speaking

    See? You can't have a reference to a reference.

  • LHS Cow speaking

    The variable n is just another name for m. So initializing o with n is the same as initializing o with m. And that means that n, m, and o are all names for the same piece of data.

  • Hedgehog speaking

    …what?!?

  • LHS Cow speaking

    I guess now you see why there was a video!

(When logged in, completion status appears here.)