references,, if i make a reference..does that mean that all im doing is making something that shares the same address? this isnt clearly stated in any tutorials im doing
Code:int var; int &ref = var;
references,, if i make a reference..does that mean that all im doing is making something that shares the same address? this isnt clearly stated in any tutorials im doing
Code:int var; int &ref = var;
Yes.
Code:#include <iostream> int main (void) { int var = 42; int& ref = var; std::cout << "Address of var: " << &var << "\nAddress of ref: " << &ref << "\n\nValue of var: " << var << "\nValue of ref: " << ref; return 0; } /* Address of var: 0x22ff74 Address of ref: 0x22ff74 Value of var: 42 Value of ref: 42 */
Last edited by whiteflags; 06-01-2006 at 08:16 PM.
And is of the same type, yes.
That way you could use ref and var from your example interchangeably.
References are most often used in functions to take an object as an arguement, without making a copy of it.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
Right.
The most common use of references is when function must change more than one variable. Most beginning books will show a Swap(X,Y) example, where the function swaps the X & Y values. In order to do that, you need to use references or pointers.
It's often useful to pass a reference to an array or structure into a function so that your function can change any of the variables in the array/structure.
Pointers and references both allow a function to "get to" the actual variable in memory. The syntax for references is simpler than pointers. And when you have a choice, references are generaly preferred over pointers.