How does the following code work in C++? Is it logical?
const int &ref = 9;
const int &another_ref = ref + 6;
Why does C++ allow literal initialization for const references when the same is not permitted for non-const references? E.g.:
const int days_of_week = 7;
int &dof = days_of_week; //error: non const reference to a const object
This can be explained by the fact that, a non-const reference can be used to change the value of the variable it is referring to. Hence, C++ does not permit a non-const reference to a const variable.
Could this be a possible explanation? C++ does not allow:
int &ref = 7;
Because that is not logical, but:
const int &ref = 7;
Is almost equivalent to:
const int val = 7;
So literal initialization is permitted for const variables.
P.S.: I'm currently studying Lippman's C++ Primer.
See Question&Answers more detail:os