Understanding reference variables in C++

Apr 19, 2012 at 8:18pm
Hi,

I have these two functions one of them using a reference variable and the otherone using a
regular variable and I get the same ecxact result if I pass the same paramter when called.


1
2
3
4
5
void func1(int &num1)
{
    num1 = num1 + 3;
    cout <<endl << "Function 1: " << num1 <<endl;
}



1
2
3
4
5
void func2(int num2)
{
    num2 = num2 + 3;
    cout <<endl << "Function 2: " << num2 <<endl;
}



1- Why would you use on instad of the other?

2- Why would you use reference variables instead of regular variables?

3- Can someone explain reference variables?

Thanks a lot
Apr 19, 2012 at 8:38pm
Instead of having the output inside of the function try writing main like this for both examples you have listed:
1
2
3
4
5
6
7
8
9
10
11
int main(int argc, char *argv[])
{
    int number = 6;
    func1(number); //YOUR FUNCTION CALL GOES HERE
     cout << number;
     
     cin.sync();
     cin.ignore();

    return EXIT_SUCCESS;
}
Last edited on Apr 19, 2012 at 8:41pm
Apr 19, 2012 at 8:48pm
I changed it but it didn't make a difference.

Thanks
Apr 19, 2012 at 8:58pm
The difference is that when you pass a variable into a function by reference you are modifying the variable at it's base address. Any changes you make to that variable inside of that function are reflected on the original. In your second example the system makes a copy of the variable for use within that function, any changes to it are not done to the original variable.
Apr 20, 2012 at 1:42am
Ok, starting to make sense, by reference basically modifies the original variables value. I will practice to see this more in depth.

Thanks a lot for your help
Apr 20, 2012 at 2:08am
reference basically modifies the original variables value
A reference IS the original variable. It's not like the original, or have some special property that makes it do something to some other variable that it is supposed to mean, it is the actual variable. All a reference is... is another "name" or "label" for some object (variable) that already exists.

Once you see code in this way, things are much clearer. It may take a little getting used to.

Hope this helps.
Last edited on Apr 20, 2012 at 2:08am
Apr 20, 2012 at 1:16pm
Ok, I now understand what a reference variable does but I still don't see where, when or why would you use this type of variables, I cannot think of any unique situation where this would fit.

Can someone be so kind an show me where, when or why a reference variable would be used?

When would you say, now I need a reference variable?

Sorry if my question doesn't make too much sense. Thanks a lot for dealing with this type of questions.
Apr 20, 2012 at 1:22pm
When you're doing stuff like recursive programming passing by reference helps cut down on the amount of overhead caused by having to copy the value to a stack at every iteration of the function. It also cuts down on the amount of typing you have to do since you don't have to explicitly tell the variable to return and keep track of it all of the time.
Apr 20, 2012 at 1:29pm
Alright, well as Computergeek01 has already stated, move your output lines to outside of the functions... So:
1
2
3
4
5
6
7
8
9
void func1(int &num1)
{
    num1 = num1 + 3;
}

void func2(int num2)
{
    num2 = num2 + 3;
}


Then call your functions and then when your function returns, output the input parameter like so. (I know you already said you did this, but you didn't see what he was talking bout so you did something incorrectly.

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(int argc, char *argv[])
{
    int number = 6;
    func1(number); 
     cout << number; //Number is 9 here after function returns...
    func2(number); 
     cout << number; //Number is STILL 9 here after function returns...
     
     cin.sync();
     cin.ignore();

    return EXIT_SUCCESS;
}


When you pass a variable by value, you cannot modify its value inside the function. If you need to be able to modify the value then you would pass by reference.


Without references the following function would not be able to do anything with the firstName and lastName variable inside the function that would live outside the function. By passing by reference you can modify the actual firstName and lastName variable inside the function (because references are just another name for the object).
void GetInputData(string &firstName, string &lastName);

Apr 20, 2012 at 1:56pm
Without references the following function would not be able to do anything with the firstName and lastName variable inside the function that would live outside the function. By passing by reference you can modify the actual firstName and lastName variable inside the function (because references are just another name for the object).
void GetInputData(string &firstName, string &lastName);


But would this do the same thing

1
2
3
4
5
6
7
8
void GetInputData(string firstName, string lastName);
{	
	string firstN = firstName;
	string lastN = lastName;

	// then use firstN and lastN in the rest of your code

}


If the main use for reference variables is to better manage memory and for less stress to the computer I got it.

I know I know, I'm almost there...

Thanks a lot for being patient.
Last edited on Apr 20, 2012 at 1:58pm
Apr 20, 2012 at 2:03pm
I have these two functions one of them using a reference variable and the otherone using a
regular variable and I get the same ecxact result if I pass the same paramter when called.


Call them more than once.
Apr 20, 2012 at 2:21pm
But would this do the same thing

No it wouldn't.

When you pass by value, your parameter allocated enough memory for the data type passed in. It then creates a copy of whatever variable passed in:
1
2
3
4
5
6
void DoStuff(int a)  // Allocate memory for int.  Copy whatever is passed in into that allocated slot.
{
   a += 5;  // Operation performed on that copy
}

// Here, outside of the scope, the copy doesn't exist (or isn't reachable) 


Let's put that into some perspective:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void DoStuff(int a) 
{
   a += 5; 
}

int main()
{
   int my_int = 1;
   DoStuff(my_int);

   // In this example, DoStuff allocated space for an int, refers to it as 'a'.
   // Then, it copies the contents of my_int (i.e. 1) into that allocated space.
   // It performs operations on the instance in the newly allocated space.
   // Meaning operations aren't performed on the variable held at the space allocated to my_int.

   cout << my_int;  // This will still equal 1
}


If you pass it by reference, you pass the address of the parameter. You don't allocate a new section of memory and all operations are performed on whatever is at the address passed in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void DoStuff(int &a) 
{
   a += 5; 
}

int main()
{
   int my_int = 1;
   DoStuff(my_int);

   // In this example, the memory address of my_int is passed into DoStuff.
   // In the scope of the function, this is herein referred to as 'a'.
   // Any operations are performed directly on the value at that address, not a copy.

   cout << my_int;  // This will equal 6
}


Hopefully that helps.
Last edited on Apr 20, 2012 at 2:22pm
Apr 20, 2012 at 2:24pm
You use references when you would otherwise use a pointer, but don't want a pointer cause you have references (or can't get a pointer because you're dealing with a temporary value).
Apr 20, 2012 at 3:04pm
actually
or can't get a pointer because you're dealing with a temporary value
this is actually valid (at least for string literals). In most any other case however, if you can get a reference you can get a pointer. References have to be initialized. see below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <string>
#include <fstream>

using namespace std;

void function1(const std::string &str);
void function2(const char * str);
void function3(int &);
void function4(int *);

int main()
{
	function1("standard string call"); //ok
	function2("const char * call");    //ok
	function3(3); //error: initial value of reference to non-const must be an lvalue
	function4(&3);//error: expression must be an lvalue or a function designator
	int a(5);
	function3(a);  //ok
	function4(&a); //ok
	return 0;
}

void function1(const std::string &str)
{
	cout << str << endl;
}
void function2(const char * str)
{
	cout << str << endl;
}

void function3(int &n)
{
	cout << n << endl;
}
void function4(int *n)
{
	cout << *n << endl;
}
Last edited on Apr 20, 2012 at 3:05pm
Apr 20, 2012 at 4:52pm
Thank you all very much for the good explanations that really helped me a lot.

Topic archived. No new replies allowed.