Explain Reference Variable in C++ with example
Reference Variable:
C++ introduces a new kind of variable known as the reference variable. A reference is an alias or an alternative name for an existing variable. All operations applied on reference variables are also applied on original variable. The address of a reference variable is same as the address of the original variable. Reference variable looks like ordinary variable and behaves like pointer variable. A reference variable can be defined as:
Datatype &ref_varible = ori_varible;
Eg int a=5;
int &b = a;
cout<<a<<b; // output will be 5 5.
b= 20;
cout<<a<<b; // output will be 20 20.
Where b is a reference variable of a and a is a referent.
The following points can be noted about reference parameters.
• A reference can never be null. It must always refer to a valid object or variable
• Once a reference variable is created for one variable it cannot be reference variable for another variable.
• Reference never takes any extra space in memory.
• Reference has to be initialized while declaring only.
Limitation: A variable(referent) can have more then one references but one reference variable can have
only one referent.
Labels: C++