Kindly advise what exactly happens when i write int &b = a and how is it different from the first declaration
In the example below:
int a;
int & b = a;
The b
variable refers to the memory address of the a
variable. The variable b
is just an alias for a
.
and also when to use which.
A common usage of references is to avoid copying large objects. Rather than passing (copying) the large object, you pass a reference to it.
const std::string& Get_Tree_Name()
{
static std::string name = "Eucalyptus";
return name;
}
The above function returns a reference to a static string inside the function. So rather than copying the string after the function exits, it is passing a reference. In general, a reference would occupy less space than the std::string
object.
Another usage is when a function modifies its parameter:
void Get_Pi(double& pi_value)
{
pi_value = 3.14159264;
}
int main()
{
double my_pi = 0.0;
Get_Pi(my_pi);
}
In the main
function of the above example, the code in the Get_Pi
function is actually modifying the my_pi
variable in the main
function, because of the reference mechanism.
Without the references, the Get_Pi
function would modify a copy of the my_pi
variable and not the original variable, since parameters are passed by copy.
Pointers vs. references
Another alternative for a function to modify its parameter is to pass the parameter by pointer. One issue with using a pointer is that pointer can point to anything and not necessarily a variable.
Passing a reference means that the object must exist. A reference, unlike a pointer, doesn't need to be validated during run-time. The compiler performs the checking. This is important in safety critical systems.