C++ Programming: Objects, RAII and the STL ยท C++ Basics

References

A reference is another name for an existing variable. Pass by reference to let a function change the caller's variable without pointers.

references.cpp

#include <iostream>
using namespace std;

void add_bonus(int &score) {     // a reference: another name for the caller's variable
    score += 10;
}

void add_bonus_copy(int score) {
    score += 10;
}

int main() {
    int points = 50;
    int &alias = points;         // alias and points are the same variable
    alias = 60;
    add_bonus_copy(points);
    add_bonus(points);
    cout << points << endl;
    return 0;
}

Step by step

  1. points is created on the stack with the value 50.
  2. alias is not a copy: it is another name for points.
  3. Writing to alias writes to points: 60.
  4. add_bonus_copy gets a copy of points.
  5. Only the copy becomes 70.
  6. add_bonus_copy() has finished, so its variables are gone.
  7. add_bonus(int &score): score is points itself, not a copy.
  8. points changes from 60 to 70.
  9. add_bonus() has finished, so its variables are gone.
  10. It prints 70.
  11. The method returns 0.
  12. 70: only the reference version changed the caller's variable.