suppose I have a function which accept const reference argument pass,
int func(const int &i)
{
/* */
}
int main()
{
int j = 1;
func(j); // pass non const argument to const reference
j=2; // reassign j
}
this code works fine.according to C++ primer, what this argument passing to this function is like follows,
int j=1;
const int &i = j;
in which i is a synonym(alias) of j,
my question is: if i is a synonym of j, and i is defined as const, is the code:
const int &i = j
redelcare a non const variable to const variable? why this expression is legal in c++?
The reference is const, not the object. It doesn’t change the fact that the object is mutable, but you have one name for the object (
j) through which you can modify it, and another name (i) through which you can’t.In the case of the const reference parameter, this means that
maincan modify the object (since it uses its name for it,j), whereasfunccan’t modify the object so long as it only uses its name for it,i.funccould in principle modify the object by creating yet another reference or pointer to it with aconst_cast, but don’t.