C++ References

A reference is an alias, or a second name, for an existing variable. Once created, the reference and the original variable point to the same value in memory, so changing one changes the other. References make code cleaner and are especially useful when passing data to functions.

Creating a Reference

You create a reference by adding an ampersand (&) to the type when you declare the variable. The reference must be attached to an existing variable at the moment it is created.

A reference is another name for the same value

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";
  string &meal = food;   // meal is a reference to food
  cout << food << "\n";
  cout << meal << "\n";
  return 0;
}
// Output:
// Pizza
// Pizza

They Share the Same Value

Because a reference and its variable are the same thing under two names, updating either one updates both. This is different from copying a value, where the copy would be independent.

Changing the reference changes the original

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";
  string &meal = food;
  meal = "Burger";   // change through the reference
  cout << food;      // the original also changed
  return 0;
}
// Output: Burger

Rules to Remember

  • A reference must be initialized when it is declared; you cannot create an empty reference.
  • Once bound to a variable, a reference can never be changed to refer to a different variable.
  • A reference is not a copy; it shares the same memory as the original.
FeatureReferencePlain copy
Shares memoryYesNo
Changes affect originalYesNo
Must be initializedYesNo
Note: References are commonly used with functions so a function can work directly on the caller's variable instead of a copy. You will see this again in pass-by-reference.

Exercise: C++ References

What must happen at the moment a C++ reference variable is declared?