![]() |
VOOZH | about |
Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable.
Return by reference is very different from Call by reference. Functions behaves a very important role when variable or pointers are returned as reference.
dataType& functionName(parameters); where, dataType is the return type of the function, and parameters are the passed arguments to it.Below is the code to illustrate the Return by reference:
x = 20 The address of x is 0x7fff3025711c a = 20 The address of a is 0x7fff3025711c b = 20 The address of b is 0x7fff3025711c x = 20 The address of x is 0x7fff3025711c a = 13 The address of a is 0x7fff3025711c
Since reference is nothing but an alias(synonym) of another variable, the address of a, b and x never changes.
Below is the code to illustrate the Return by reference:Note: We should never return a local variable as a reference, reason being, as soon as the functions returns, local variable will be erased, however, we still will be left with a reference which might be a security bug in the code.
10