Why pass by ref when you can pass by memory location?

Hi All,

I have been playing around a little with the C++ references, and I wonder - why would you use a reference over just passing the variable's memory location?

Is it simply just for ease of writing code? If so, wouldn't it just be harder as you need to keep track of two variable names?

Example

int i=0;
void incFunction (int &myInt) {
myInt++;
return;
}

EDIT:
called in main : incFunction(&i);

would increment the int the same as

Example 2

int i=0;
int &iRef = i;
void incFunction (int &myInt) {
myInt++;
return;
}


EDIT:
called in main : incFunction(iRef);



Any insight would be great :)

Steve
Last edited on
In the first example, assuming incFunction is actually called with i as an argument, you've passed by reference, not by memory location.

And of course with the second, there is no need for the iref alias if you want to pass i by reference to incFunction.

There are no memory addresses used in this code.
Sorry yes I left calling out.. have added now

Same Q though, in the first example I am passing &i to the function, which achieves the same as passing the ref to it ?
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.
Last edited on
Thanks Ganado,

So you would use this in the case of objects (rather than basic data types),

That makes sense :)

Steve
Topic archived. No new replies allowed.