Consider the following program:
program1.cpp
#include <iostream>
int main() {
const int bar = 5;
int&& i = const_cast<int&&>(bar);
i = 0;
std::cout << bar;
return 0;
}
When I compiled and ran this with
g++ program1.cpp -Wall -Wextra -Wpedantic -o program1
./program1
the output was 5.
But when I compiled and ran this program, which I also expected to output 5:
program2.cpp
#include <iostream>
class example{
public:
const int bar;
example(const int i) : bar(i){}
void foo() const{
int&& i = const_cast<int&&>(bar);
i = 0;
}
};
int main() {
example e(5);
e.foo();
std::cout << e.bar;
return 0;
}
g++ program2.cpp -Wall -Wextra -Wpedantic -o program2
./program2
The output was 0.
Why is the result different when the const variable is in a class?