A reference is an alias for an existing object. We can use references same as a variable almost all the places where can we variable. We can use references to read or modify the object being referenced.
Lvalue reference is a type of reference which used to reference an lvalue. While creating an lvalue reference, we need to specify the type that should match the type of object being referenced, this is called lvalue reference type. For example,
int& ref
double& ref
const int&refType of reference should match the type of object, otherwise compilation fails. Non-const type reference can’t be used to reference const type object (which makes sense as we can’t modify a const object through a non-const reference.)
Create Lvalue Reference Variables
We can use lvalue reference type to initialize reference variables. These variables act as references to the lvalues.
For example,
int main(int argc, char const *argv[])
{
int value{1};
int &val_ref{value};
std::cout << value << "\n";
std::cout << val_ref << "\n";
return 0;
}In this example, we create int& reference type variable val_ref that references an int lvalue expression value. We can then use value and val_ref synonymously.
Note
Using
&with type or with variable does not matter for compiler. However, it is preferred to attach&with the type.
Initialization of a reference is mandatory otherwise compiler cries. In the initialization (above program), the reference is bound to int lvalue. This is called reference binding. int lvalue which is referenced is called referent.
References can’t be changed to reference another object
We can’t modify referent after the reference is initialized. Following program shows this:
int main(int argc, char const *argv[])
{
int value{1};
int &ref{value};
std::cout << value << ref << "\n";
int anothervalue{2};
ref = anothervalue;
std::cout << value << ref << "\n";
return 0;
}ref = anothervalue does not change ref to reference anothervalue, instead anothervalue’s value which is 2 is assigned to value as ref is referencing value.
Note
Reference can’t be used to reference another reference. Because:
Lvalue reference references an identifiable object and references are not object.