Functions · Language foundations
References
Another name for an object. Follow what changes in the caller.
Two names. One object.
A reference is another name for something already stored, such as the integer in a score variable. C++ calls that stored thing an object. With int& value, value names the original integer rather than receiving a separate copy. A function using that name can change the original score. The caller is the code that asks the function to run. Start with the symbols or the worked example before the optional check.
Read the function one piece at a time.
void means this function sends no result number back. incrementOriginal is its name. Inside parentheses, int& value says its input name refers to the original whole-number variable; int value without & would be a separate copy. The braces contain its instructions. Here ++value is an instruction that adds one to that integer. The caller creates score with 4, then incrementOriginal(score) asks the function to run with score as its input. Both names refer to the same stored number, so score becomes 5. The function definition describes the job; the call runs it. The definition belongs outside main; the last two instructions belong inside main.
void incrementOriginal(int& value) {
++value;
}
// Inside main:
int score = 4;
incrementOriginal(score);Work with the original.
Sometimes changing the original is the point: incrementing a score should update the caller’s score. A const reference can also provide read-only access without copying a large object. Use a value parameter when you want an independent value; a reference is a deliberate connection to something that must stay alive.
Which function changes score?
The value parameter is a local copy. The reference parameter aliases score. After both calls, score is 5: only incrementOriginal changes it.
void incrementCopy(int value) { ++value; }
void incrementOriginal(int& value) { ++value; }
int score = 4;
incrementCopy(score);
incrementOriginal(score);An alias adds a name, not a value.
Both names lead to the same int object. Writing through either name updates that one value. This is a conceptual diagram, not a claim about how the compiler stores references.
- int object
- value: 5
- score
- caller’s name
- value
- reference parameter
- score leads to int object (names)
- value leads to int object (names)
Assignment changes the object.
After int& alias = a, alias = b assigns b’s value into a. It does not rebind alias to b. A pointer can be reassigned to another address; this reference keeps naming a.
int a = 4;
int b = 9;
int& alias = a;
alias = b;
++alias; // a is 10; b is still 9A name cannot keep a local alive.
Returning a reference to an ordinary local variable leaves the caller with a dangling reference after that function returns. The local’s lifetime has ended. Return a value when the result should be a new independent object.
Further reading
Trusted resources for the rules and APIs discussed in this guide.