What are C++ references? Why use them?
Archive - Originally posted on "The Horse's Mouth" - 2010-07-02 21:16:15 - Graham EllisC++ References let you give variables alternative names. For example, if you write
int & jones = flossie;
then "jones" becomes an alternative name for flossie in the current scope. If you assign something new to jones, you're not going to make the variable into an alternative name for something else - you're actually going to change the value that's being held under (both) names. You can see a worked example in [source code here].
Why do you want to give variables alternative names in this way?
One reason is that you're wanting to loop through every member of an array - perhaps an array of objects too, where the variable names to describe a memory location are complex. Rather than repeat the complexity time after time in your code, a reference is a lighweight alternative to a pointer to simplify it. For example, you might write:
for (int i=1; i<length; i++) {
Shape * ¤t = candidates[i];
sofar = current->heavier(sofar);
and you can then keep making further references to current rather than the more complex candidates[i] for the rest of the loop too.
There's a further example that compares and contrasts references and pointers [here], and one that uses both reference and pointers to array members [here]