CS 70

Warning: C++ Is Not Java

  • LHS Cow speaking

    As you saw in the previous example, references give us Java-like functionality.

  • RHS Cow speaking

    Importantly, however, they are not the same as Java references!

A regular variable specifies a particular location in memory. The location holds a value and that value can change over time, but the location itself is fixed for the life of the variable.

Likewise, a reference refers to a specific location in memory. The location holds a value and that value can change over time, but the location itself is fixed for the life of the reference.

So, while Java references

  • Can be changed to point to different objects over time, and
  • Can be null (not point to anything).

C++ references

  • Always refer to the same location for their entire lifetime, and
  • Always refer to a real location in memory.

If you think you're changing a C++ reference, you're actually changing the value at the location it refers to. This is exactly the same as what happens when you change a regular variable, you don't change where in memory it is, you change the value at the location it refers to.

  • Horse speaking

    Hay, wait, so you're making out like references and regular variables are alike because both refer to a location in memory and can't move to refer to a different location, but you're saying that references are also different from regular variables. What gives?

  • LHS Cow speaking

    The difference is that a regular variable has storage that is allocated, then initialized, then used, then destroyed, then deallocated. In contrast, a reference just piggybacks on the storage (and initialization) of something else. It's not allocated, initialized, destroyed, or deallocated in its own right. It's just a name for something that already exists. An alias.

  • Duck speaking

    Okay, so a reference is like a nickname? But doesn't it require some memory to store the nickname?

  • LHS Cow speaking

    Actually, no. The nickname is just a name for something that already exists. It doesn't need any memory of its own. It's just a name for something that already exists.

  • Bjarne speaking

    In essence, yes. References do not consume any memory that you are allowed to access.

  • Rabbit speaking

    In practice, behind the scenes, sometimes the system may need to use some memory to make references work, but it's an under-the-hood how-C++-works-inside detail.

  • LHS Cow speaking

    Shhhhh... we don't need to worry about those kinds of details—even the C++ standard doesn't specify how references should be implemented. So we won't draw any extra memory for any that under-the-hood data in our diagram because we can't actually access or interact with it.

(When logged in, completion status appears here.)