Junior
What is a reference in C++?
sobes.tech AI
Answer from AI
A reference is an alias (alternative name) for an existing object.
Main characteristics:
- Initialization: Must be initialized at the time of declaration.
- Immutability: After initialization, the reference cannot be changed to refer to another object.
- No null: Cannot be "null," always refers to a valid object.
- Cannot be reseated: Assigning a new value through the reference changes the object it refers to, not the reference itself.
- Used in parameter passing: Often used to pass objects by reference in functions to avoid copying and to modify the original object.
Example:
int x = 10;
int& ref = x; // ref is a reference to x
ref = 20; // Changes the value of x
// x is now 20
Comparison with pointers:
| Characteristic | Reference | Pointer |
|---|---|---|
| Initialization | Mandatory | Not mandatory |
| Null value | Impossible | Possible (nullptr) |
| Reseating | Impossible | Possible |
| Access syntax | Like a normal object | Dereferencing (*) |
| Memory allocation | Does not occupy its own memory (alias) | Occupies memory to store address |
References provide a safer and more convenient alternative to pointers in many cases, especially when passing arguments by reference or returning references from functions.