I’ve always wondered is there a way to have a class member without using getters that can only be modified by it’s class?
What I’m thinking of is something like this.
class A
{
public:
crazyconst int x;
void doStuff()
{
// Gettin' stuff done
x = someValue; // OK
}
};
int main(int argc, char** argv)
{
A a;
a.x = 4; // ERROR
}
So it’s visible, but read-only for everyone beside its class.
The answer is no you can’t do this without a getter of some sort. However, you can make the getter reusable and you can make the simple syntax of a field work (mostly), without parentheses.
(C++11 required)
C++03 version: http://ideone.com/8T1Po
But beware, this will compile but not work as expected:
OTOH, this should be fine: