When do you use reference? vs normal variable?

I often have a mistake on declaring a variable by copy.

I am used to c# and even though I understand the copy by value and copy by reference thing, I still cant find a practical way on when do you use the reference when declaring a variable.
Last edited on
A reference is really just an alias; it's another name for a variable in your program. A reference must be initialized when it's defined and it cannot be changed to refer to a different variable during the lifespan of a program.

To answer your question, you use references when you are passing large objects to a function as it results in efficiency.
Refs are the best thing that happened to me in C++. There are many practical ways to use Refs, after they are paired with functions.

Say you have to make a function to get the name of a person
1
2
3
4
5
6
7
//...
string get_name (string first_name, string last_name)
{
cin >> first_name;
cin >> last_name;
//...
}

Now we have the problem of returning two variables.
You can't do
1
2
return first_name;
return last_name;

So the two simple choices you have are:
A. Create a struct to pass as argument and return.
B. Refs

The former, however, is inefficient when compared to the latter, which is more easier to execute and runs faster.
So we do
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void get_name (string& first_name, string& last_name)
{
cin >> first_name;
cin >> last_name;
}

int main ()
{
string fs_n, ls_n;

void get_name (fs_n, ls_n);

return 0;
}


Last edited on
I see.. great explanation.. Thanks
Topic archived. No new replies allowed.