As it mentioned in another answers, a reference is inherently const.
int &ref = obj;
Once you initialized a reference with an object, you can't unbound this reference with its object it refers to. A reference works just like an alias.
When you declare a const
reference, it is nothing but a reference which refers to a const object.
const int &ref = obj;
The declarative sentences above like const
and int
is determining the available features of the object which will be referenced by the reference. To be more clear, I want to show you the pointer
equivalent of a const
reference;
const int *const ptr = &obj;
So the above line of code is equivalent to a const
reference in its working way. Additionally, there is a one last point which I want to mention;
A reference must be initialized only with an object
So when you do this, you are going to get an error;
int &r = 0; // Error: a nonconst reference cannot be initialized to a literal
This rule has one exception. If the reference is declared as const, then you can initialize it with literals as well;
const int &r = 0; // a valid approach