Consider the following:
int someA = 1;
int someB = 2;
int &a = someA;
int &b = someB;
a = b; // what happens here?
What's happening here with the references? Just curious.
Consider the following:
int someA = 1;
int someB = 2;
int &a = someA;
int &b = someB;
a = b; // what happens here?
What's happening here with the references? Just curious.
Having two reference variables equal to each other is in itself not an error. It may be confusing. However, what your code does is not setting a reference to another reference, it's altering the value of _A
from 1
to 2
, which is what's in _B
.
You can ONLY set a reference ONCE [where it is initialized]. Once it's been initialized, it will simply become an alias for the original variable.
You could do this:
int &a = _A;
int &b = _A;
and
a = b;
would store the value 1
into _A
, which already has the value 1
.
There is no error here, but I think I may know what you're confused about. The reference won't be reassigned, however the value of what it is referencing is reassigned.
So when you do a = b;
you're essentially saying this: _A = _B
, because a reference is an alias.
A reference can never be reassigned like a pointer can.
A reference can also never be null.
You can not have statements outside a function.
a = b; //compile error?
That is a statement so must be in a function:
int _A = 1;
int _B = 2;
int &a = _A;
int &b = _B;
int main()
{
a = b; //compile error? No. Now it compiles.
// As 'a' and 'b' are references.
// This means they are just another name for an already existing variable
// ie they are alias
//
// It means that it is equivalent to using the original values.
//
// Thus it is equivalent too:
_A = _B;
}
Now it compiles.