overloading assignment operator With subscript operator

user2960763 picture user2960763 · Nov 23, 2013 · Viewed 11.8k times · Source

I overloaded both subscript operator and assignment operator and I am trying to get right value to assignment operator example Array x; x[0]=5; by overloading subscript operator i can get value 0 but when i overload assignment operator it does the assignment but it doesn't use my overloaded function because vaiable 2 should have value 5.

class Array
{

public:
    int *ptr;
    int one,two;
    Array(int arr[])
    {
        ptr=arr;
    }

    int &operator[](int index)
    {
        one=index;
        return ptr[index];
    }
    int & operator=(int x){
        two=x;
        return x;
    }   
};

int main(void)
{
    int y[]={1,2,3,4};
    Array x(y);
    x[1]=5;
    cout<<x[0]<<endl;
}

Answer

It does not use your operator= because you are not assigning to an instance of Array, you're assigning to an int. This would invoke your operator:

Array x;
x = 7;

If you want to intercept assignments to what operator[] returns, you must have it return a proxy object and define the assignment operator for that proxy. Example:

class Array
{
  class Proxy
  {
    Array &a;
    int idx;
  public:
     Proxy(Array &a, int idx) : a(a), idx(idx) {}
     int& operator= (int x) { a.two = x; a.ptr[idx] = x; return a.ptr[idx]; }
  };

  Proxy operator[] (int index) { return Proxy(*this, index); }
};