Possible Duplicate:
How come a non-const reference cannot bind to a temporary object?
This program:
int fun()
{
return 1;
}
int main()
{
const int& var = fun();
return 0;
}
My question is why I must put a const befor the var definition? If not ,g++ will give me an error ,goes something like “invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’.”
what is the ‘const’ for ?
In this situation you need
constbecause reference initialization requires a variable with an address, not simply a value. Therefore the compiler must create an anonymous variable which you cannot access other than through the reference; the compiler does not want you to access the variable that you did not declare.If you would declare the variable explicitly,
constwould be unnecessary: