Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ function: pass non const argument to const reference parameter

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++?

like image 794
fuyi Avatar asked Feb 03 '12 10:02

fuyi


2 Answers

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 main can modify the object (since it uses its name for it, j), whereas func can't modify the object so long as it only uses its name for it, i. func could in principle modify the object by creating yet another reference or pointer to it with a const_cast, but don't.

like image 200
Steve Jessop Avatar answered Oct 25 '22 09:10

Steve Jessop


const int &i = j;

This declares a reference to a constant integer. Using this reference, you won't be able to change the value of the integer that it references.

You can still change the value by using the original variable name j, just not using the constant reference i.

like image 31
mcnicholls Avatar answered Oct 25 '22 08:10

mcnicholls