Junior — Middle
How can passing an argument by reference be implemented in C++?
sobes.tech AI
Answer from AI
In C++, passing an argument by reference allows the function to work with the original object rather than a copy. This is done by using an ampersand (&) after the parameter type in the function declaration.
Example of passing by reference:
void increment(int& value) {
value += 1; // modifies the original argument
}
int main() {
int a = 5;
increment(a);
// now a == 6
return 0;
}
This method is useful for:
- Avoiding copying large objects (efficiency).
- Modifying the passed data inside the function.
Important: When passing by reference, the function accesses the original object, so changes inside the function affect the argument in the call.