<pa**********@att.netwrote in message
news:11**********************@e3g2000cwe.googlegro ups.com...
Take the code:
int ival = 1024;
int &refVal = ival;
My text says "a reference is just another name for an object ... we can
access refVal through ival ..."
I understand this way of using references.
However, it does seem to me that this is not the only way references
are used.
For example:
void swap (int &v1, int &v2)
{
int tmp = v2;
v2 = v1;
v1 = tmp;
}
I don't think v2 = v1 means "v2 refers to v1". I think v2 = v1 means:
Change the integer v2 refers to by assigning it to the same value that
v1 refers to. In other words the meaning of v2 = v1 is identical to
what it would mean if the signature was (int, int) instead of (int&,
int&).
How can I tell when a reference is acting as an alias and when it
isn't?
A reference has to be initialized. You can not say:
int& refVal;
refVal = ival;
in code. The only way, that I know of, to seat refVal if declared this way
is through a constructor initialization list.
So, *anywhere* you see
SomeRef = Something
it is an assignment, not reseating the reference, unless it is the
declaration.
I.E.
int& SomeRef = A1; // Make SomeRef refer to the varaible A1
SomeRef = A1; // Store the value in A1 into the variable refered by SomeRef
So, taking your function:
void swap (int &v1, int &v2)
// At this point v1 and v2 are seated, whatever was passed into the function
{
int tmp = v2;
// make an int and give it the value that is stored in whatever
// variable v2 is a reference to.
v2 = v1;
// assign the variable that v2 points to the value that is stored in
// the variable v1 points to.
v1 = tmp;
// assign the variable that v1 points to the value that is stored in tmp
}