Re: beginner's question on reference variable
On Nov 21, 8:10 pm, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.com> wrote:
I read in textbooks and in this Usenet group that
a reference is not an object but only an alias.
consider
#include <iostream>
using namespace std;
int main()
{
int obj = 100;
int &ref = obj;
cout << ref << endl;
return 0;
}
When this program is run, will there be a memory location created
for the variable ref ? Or the compiler will replace ref with obj ?
The compiler *could* create a pointer to obj, which is "ref". In such
a case your reference is really a pointer with a different syntax. Or
it *could* optimize that pointer away (possibly even if you turn off
optimizations!), in which case there is no memory allocated for ref;
each time it sees ref, it replaces "obj".
And then some people will come and start talking about this-or-that
points which I myself don't understand.
I do not know how to check whether a variable occupies some
memory(that is, stored in memory) when a program is run.
Note that if you're thinking of memory at this point, you are not
really thinking C++ yet.
A reference is just another way of referencing the object. The fact
that it's *often* implemented as a pointer that *sometimes* takes up
stack space doesn't matter (at least until you understand the
something-or-other points the other people talk about). As far as
you're concerned, it *is* the object. You can mutate its data members
and call its member functions using ref.something() syntax. You can
assign something to it via ref = somevalue;. It's like a variable
variable - you can attach it to some other object at some other time
(usually done by putting it as a function argument). For example:
void turnintoten(int& v){
v = 10;
}
int main(){
int x, y;
turnintoten(x); //now v in the code above refers to x
turnintoten(y); //now v in the code above refers to y
....
}
Note that as far as I know there is no other way of changing a
reference so that it aliases another object, other than using it as a
function argument. For example:
int i, j;
int& ref = i;
ref = j; //it is i that is changed; ref still refers to i.