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.
Alright, all the other answers I dislike, so here’s my idea: hide the variable.
There are still ways to bypass the locking of the variable (such as
this->x), but nothing can be done for those situations.