New User

Hey guys I am new to c++.
So I wanted to know when and where reference variables are used.
How do we judge that in a function you need a reference variable.
I hope Any one will help me!
Thankz
consider this code
1
2
3
4
5
6
void function(type var){...}
int main(){
   int arg;
   funciton(arg);//or &arg
   return 0;
}

to decide whether 'type' should be int, int& or int*,
if you don't want changes made to 'var' affect 'arg', type = int
else if it would make sense not to pass anything (NULL) into 'function', type = int*
else type = int&

References are used as function parameters / return.
You need to pass by reference if you need to modify the variable passed as argument
eg:
1
2
3
4
5
6
7
8
void add_5 ( int& i )
{
    i +=5;
}
//...
int x = 1;
add_5 ( x );
// x now = 6 


You need to pass by const reference if you don't have to modify the object, if you need rvalues to be passed and the objects to be passed are big
eg:
1
2
3
4
void do_something ( const std::vector<int> &v )
{
    // a vector is expensive to copy so pass by const reference
}


Returning references is useful with class members
eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
strucu foo
{
    foo& bar ( )
    {
        // do something
        return *this; // return a reference of the object
    }
};

//...

foo object;
object.bar().bar(); // both calls to bar are applied to object 
Thanks Bazzy and hamsterman
Thanks Bazzy and hamsterman
Topic archived. No new replies allowed.