If I understand you correctly, true, doing
1 2 3 4
|
int i=0;
int &iRef = i;
iRef++;
|
is a bit redundant for such a basic example.
___________________________________
Sorry if the following is over your head or not explained well =)
It could hypothetically be helpful to do something like this:
1 2 3 4 5 6
|
BigObject stuff;
int& data = stuff.more_stuff.some_junk.trash.data;
do_stuff_with(data);
do_more_stuff_with(data);
more_functions(data);
|
So now you only need to refer to "data" and not the long stuff.more_stuff.some_junk.trash.data.
You'll find more uses for references as you delve into it more.
Everything in C++ is pass by value except for references. If you to change an object or variable that you pass to another function, you'd need to either pass a pointer to that object, or pass the object as a reference.
References can in one way be seen as the evolution of pointers. Pointers, which are in a way similar to references, are semantically confusing and serve a different purpose in modern C++ than references. A pointer can be NULL (nullptr), while a reference needs to always refer to an actual object.
Passing by
const reference also makes you not have to copy a large object when calling the function, even if you don't plan to modify it.