C++ Programming: Objects, RAII and the STL ยท C++ Basics
A reference is another name for an existing variable. Pass by reference to let a function change the caller's variable without pointers.
#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;
}points is created on the stack with the value 50.add_bonus_copy() has finished, so its variables are gone.points changes from 60 to 70.add_bonus() has finished, so its variables are gone.70.0.