In the current semester at the university we are working on OOP with C++.
I would like to understand the difference between a pointer and a reference operator.
The differences that I understand are:
1. Cannot change the object that the reference variable is binded to
2. we can use the reference variables to refer to the binded object without having to type the & operator (in contrast with the pointers where we would write *pi = 5;)
Also,does a reference variable contain the address of the object that is binded to?
In example:
int i;
int &ri = i;
Here ri contains the address of i?
And the reason why when overloading ++ operator in this example of enumeration we are using the dereference or reference(*) operators before the name of the function.
Best Answer
A reference serves one purpose: to act as an alias for an existing variable:
In this example, the addresses of
i
andri
are identical (&i == &ri
). The two names refer to the very same location in memory. Thus one of the useful applications of references is to provide an alias for a long name that it would be wasteful to retype:When you pass a function parameter by reference, it has the same effect:
Here,
parameter
serves merely as an alias ofvariable
, just as though it were defined asint& parameter = variable
. Modifyingparameter
insideincrement()
is indistinguishable from modifyingvariable
inmain()
. Furthermore—and this is quite useful—variable
does not need to be copied; so if it were of a large type such asstd::list<int>
, then passing it by reference would be much more efficient. That’s the main point ofconst
references.For the purpose of function parameters of reference type, the sanest course of action for a compiler is to use a pointer internally, as if you had written:
This is an interesting detail, and well worthwhile to remember. While it is not essential to your understanding of references, recognising this equivalence allows you to think of pointers merely as explicit references. Likewise, references are implicit pointers.