C++ pattern for class members that may only be modified in operator=()

Viewed 61

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.

1 Answers

You could mark x as private and then implement all your other methods in a class derived from foo:

class foo
{
private:
    int x;
protected:
    int y;
public:
    foo(int inp) : x(inp) {}
    foo(const foo &src) : x(src.x) {}
    foo& operator=(foo&src)
    {
         x = src.x;
         return *this;
    }
};

class derived : public foo
{
public:
    void bar()
    {
        x = 4;  // compiler error (desired)
        y = 42; // ok
    }
};
Related