11

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

iammilind
  • 68,093
  • 33
  • 169
  • 336
fuyi
  • 2,573
  • 4
  • 23
  • 46

2 Answers2

20

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.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • you mean the reference is not the object itself. then how to understand the i is a synonym of j ? does it mean i and j are the same object, because both i and j have the same physical address? – fuyi Feb 03 '12 at 11:14
  • i is an alternative reference to the object j. So a synonym. You have however said that you cannot use 'i' to alter the object it is referring to. Nothing says you can't use some other method of modifying the object i refers to. You're restricting the capabilities of i with that declaration, not trying to extend them, and that's fine. – Tom Tanner Feb 03 '12 at 11:33
  • 1
    @xiaopang: '`i`' and '`j`' are names. They both refer to the same object. Often we say that something "is" its name, or that the name "is" the object. For example I might say "I am Steve". But this is imprecise terminology, the two are not the same thing. I can also say, "'Steve' begins with a capital 'S'". That does not imply that *I* begin with a capital 'S'. The quotes around 'Steve' are there to indicate that I'm talking about the name, not the object to which it refers. `i` and `j` are synonyms because they are both names for the same object, but their properties as names are different. – Steve Jessop Feb 03 '12 at 11:59
4
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.

mcnicholls
  • 846
  • 5
  • 10