When passing a variable/object to a method, we must use an "&" symbol in the method's signature so we can modify that variable/object and not a copy of it in another memory location.
Ex.
void increment(int &myNum){
myNum++;
}
int main () {
int x = 5;
increment(x);
// Now x is 6
return 0;
}
Had I not put the '&' symbol in front of the variable, x would still be 5 in my main. What does the '&' symbol do that tells the function that myNum will have the same l-value as x?
I understand it has 2 uses:
1. To make an alias
2. To take the address of the variable
So I said "increment(int &myNum)", now is that saying myNum will now be an alias to whatever was passed to increment?
If I'm right, okay cool.
If I'm wrong, please explain the theory of what's going on. I don't want to just hear it's taking the address, I want to understand how, I want to understand the syntax.
When you pass x by reference, myNum uses the same address as x. So if you change myNum then you change x. When you pass by value, whatever x's address contains is copied into another address for myNum. Does this help?
The ampersand(address-of operator) is used to indicate that that object will have the same address as the one it's constructed from. You may think of it as an internal wrapper for a pointer, with all the operators overloaded to use only the value pointed to by the pointer, except it's constructor, which initializes the pointer to the address of the variable passed to it.