I would like to be able to declare a class member that can only be modified in constructors or in the assignment operator. The const declaration does not work because of the assignment issue.
class foo
{
const int x;
public:
foo(int inp) : x(inp) {}
foo(const foo &src) : x(src.x) {}
foo& operator=(foo&src)
{
x = src.x; //compiler error (not desired)
return *this;
}
void bar()
{
x = 4; //compiler error (desired)
}
};
Does anyone know an elegant design pattern that can accomplish this? I find const members to be extremely limited in their usefulness. But if there were a pattern that allowed for modifying a member only in operator= while giving errors anywhere else it was modified, I would probably make a lot of use of it.