Understanding C++ references
When we pass values to a function or return values from a function, that is exactly what we are doing – passing/returning by value. What happens is that a copy of the value held by the variable is made and then sent to the function, where it is used.
The significance of this is twofold:
- If we want the function to make a permanent change to a variable, this system is no good to us.
- When a copy is made to pass in as an argument or returned from the function, processing power and memory are consumed. For a simple
int
, or even perhaps aSprite
, this is insignificant. However, for a complex object, perhaps an entire game world (or background), the copying process will seriously affect our game’s performance.
References are the solution to these two problems. A reference is a special type of variable. A reference refers to another variable. Here is an example to help you understand this better:
int numZombies ...