void SampleMethod(int& val)
{
val++;
}
int main()
{
int a = 5;
int b = 10;
int& ref = a; //ref bound to a and has a's value i.e. 5
ref = b; // ref doesn't point to b now but just sets the value of a to 10
SampleMethod(a); // a gets incremented inside the function and becomes 11
cout << "Result: " << endl << a << endl << b << endl;
return 0;
}
The reference doesn't track b, so b doesn't change it's value to 11. It's similar to something like:
int* ref = &a;
*ref = b;
One probable way to mitigate this possible confusion that references could be set to track another variable after being initialized (they can't!) is to use braced initializers for initializing references. So
int& ref{a}; //Initializes reference and binds it to a
ref = b; // Changes the value of the underlying object (a) not setting it to b