previous | start | next

The Non-Member operator+

Here is the member operator+ that works for

For

Pair p1(2,3);
Pair p;

p = p1 + 1;      
   

Here is the member operator+ that works

Pair Pair::operator+(d)
{
  int xval = x + d;
  int yval = y + d;

  return Pair(xval, yval);
}

The non-member operator+ that would work for

Pair p1(2,3);
Pair p;

p = 1 + p;      
   

might be expected to be

Pair operator+(int d, const Pair& other)
{
  int xval = d + other.x;
  int yval = d + other.y;

  return Pair(xval, yval);
}

But other.x is illegal!

Since this operator+ is not a member function it can't access the private members of Pair!



previous | start | next