-
Const and References
First Code : -
Code:
#include<iostream>
using namespace std;
int main()
{
int i = 10;
const int &j = i;
}
how can i create a reference to a const, even when the variable of which the reference i am creating is not const. and thats where my problem starts
Second Code :-
Code:
#include<iostream>
using namespace std;
int main()
{
int i = 10;
const int &j = i;
cout<<i<<j;
j = 20;
cout<<i<<j;
getchar();
}
now, i get error at j=20
Third Code:-
Code:
#include<iostream>
using namespace std;
int main()
{
int i = 10;
const int &j = i;
cout<<i<<j;
i = 20;
cout<<i<<j;
getchar();
}
and this is working
please i need explaination!
-
The reference to const just means that you promise not to change the value through that reference. The original variable is not affected in any way. That is why you can make j a reference to const when i is not const. The const in the j declaration only applies to j.
It's like if a husband and wife are watching the TV and the husband has the remote. The wife can watch the TV all she wants, it doesn't stop the husband from changing the channel.
That is also why the third code works. The i variable is not const, so you can change it. The fact that you created a reference to const named j and had it refer to i is irrelevent.
-
i is not const, so you can change it. j is an alias of i, but you may not change it, because it is const (you may not use the alias to modify the original - it's a read-only alias). If you want to catch attempts of modifying i, make it const too.
const references usually come to play, when you want to pass a reference to a function for performance considerations (no copy) but want to be sure that the function won't modify the original value (as a non-const reference could). But that's only as far as this particular function is concerned.
-
wow!, awsome explaination !
and now just for confirmation
isnt this code non-sense?
Code:
#include<iostream>
using namespace std;
int main()
{
const int i = 10;
int &j = i;
}
-
Correct, it shouldn't compile.