Tuesday 4 December 2012

Reference variable in c++

C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable. While this may not sound appealing at first, what this means is that when you declare a reference and assign it a variable, it will allow you to treat the reference exactly as though it were the original variable for the purpose of accessing and modifying the value of the original variable--even if the second name (the reference) is located within a different scope. This means, for instance, that if you make your function arguments references, and you will effectively have a way to change the original data passed into the function. This is quite different from how C++ normally works, where you have arguments to a function copied into new variables. It also allows you to dramatically reduce the amount of copying that takes place behind the scenes, both with functions and in other areas of C++, like catch clauses.

Declaration is,
int& ref = <some_int_variable>;

For Example,
int x; 
int& foo = x; // foo is now a reference to x so this sets x to 56 
foo = 56; 
std::cout << x <<std::endl;

What are the difference between Reference Variable and conventional pointers?

> A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
> A pointer can point to NULL while reference can never point to NULL
> You can't take the address of a reference like you can with pointers
> There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).

End Line: Beware of references to dynamically allocated memory. One problem is that when you use references, it's not clear that the memory backing the reference needs to be deallocated--it usually doesn't, after all. This can be fine when you're passing data into a function since the function would generally not be responsible for de-allocating the memory anyway. 

On the other hand, if you return a reference to dynamically allocated memory, then you're asking for trouble since it won't be clear that there is something that needs to be cleaned up by the function caller.

No comments:

Post a Comment