is reference really an alias?

i did the following and found out that memory address of a and c are the same. So does this means that both variable and its reference have the same memory location or should i say one variable has two names? I do know that reference has no memory of its own .. so what actually is a reference is it a variable of just another name of an object?
int main()
{
int a;
int *b = &a;
int &c = *b;
c = 10;
cout<<&b<<ends<<&a<<ends<<&c<<endl;
}
OUTPUT:
002FFD04 002FFD10 002FFD10
It looks to me as though you haven't created a reference with that code. The & (the way you have used it) just takes the address of a variable. A reference has the & at the end.

Google C++ reference example.

AFAIK a reference is more type safe because always 'points' a particular variable or object, where as a pointer can be made to point at something else. A reference is really another name for a variable or object.

HTH
c is a valid reference in his example @ TheIdeasMan.

So does this means that both variable and its reference have the same memory location or should i say one variable has two names?


Aren't both of those exactly the same?

The variable is a spot in memory that is given a name. So if two names share the same memory, that makes them different names for the same variable.


so what actually is a reference is it a variable of just another name of an object?


Conceptually, yes. That's all it is.
MyClangers++; :D
The standard says

8.3.2 References (1)
[ Note:
A reference can be thought of as a name of an object. — end note ]
. So yes, it is an alias.

Note - The standard also states
4 It is unspecified whether or not a reference requires storage
So finally we can conclude that a reference may or may not require storage but saying that it is just another name for a variable is not false
but it may not be always true

Thank You Everyone
but it may not be always true


When is it not true that a reference is another name for something?
A reference is always another name for some object.

The issue is how the reference works. The standard makes room for different considerations when implementing it.

For example, in the following code, it is very easy for the compiler to optimize the existence of y away. You could do the same by just replacing every instance of "y" with "x" and deleting line 2:

1
2
int x = 12;
int& y = x;

However, in the following code, the reference may not always be an alias to the same object:

1
2
3
4
void quuxify( int& n )
  {
  n = n * 7;
  }

because it may be used like this:

1
2
3
int a=2, b=3;
quuxify( a );
quuxify( b );

The compiler has a couple of options. It could inline the function, and make it a true alias, which gets optimized away (the same as if you just wrote a = a * 7; and b = b * 7;. Or it could implement it as a pointer underneath.

From your point of view, however, it is still an alias for some other object.

Hope this helps.
Topic archived. No new replies allowed.