Can a variable be locked to prevent changes to it in c++?
c++, constants, variables
Solution
Alright, all the other answers I dislike, so here's my idea: hide the variable.
#define READONLY(TYPE, VAR) const TYPE& VAR = this->VAR //C++03
#define READONLY(VARIABLE) const auto& VARIABLE = this->VARIABLE //C++11
class myClass {
int x; // This should be prevented to being changed most of the time
int y; // Regular variable
myClass() :x(1), y(2) {}
void foo1 () {// This can change x
x++;
y++;
}
void foo2 () {// This shouldn't be able to change x
READONLY(x); //in this function, x is read-only
x++; //error: increment of read-only variable 'x'
y++;
}
};
There are still ways to bypass the locking of the variable (such as `this->x`), but nothing can be done for those situations.
Problem
I am using a member variable and at some point of the program I want to change it, but i prefer to "lock it" everywhere else to prevent unintended changes. Code to explain: ``` class myClass { int x; // This should be prevented to being changed most of the time int y; // Regular variable myclass() {x = 1;} void foo1 () {x++; y++;} // This can change x void foo2 () {x--; y--;} // This shouldn't be able to change x // I want it to throw a compile error }; ``` The question is: Can it be achieved in some way? Something like permanent const_cast? I know I could use constructor initialization list and constant right away, but i need to change my variable later.