previous | start | next

Overloading operator+ as Member: 1

Suppose we want to overload operator+ for the Pair class.

        Pair p1(1,2);
        Pair p2(5,5);
        Pair p;

        p = p1 + p2;

        p should be the pair with x=6, y=7
     

If we make this operator a member function of Pair, then p1 + p2 will be equivalent to calling the operator+ method on p1 with argument p2; (so this operator+ will have only 1 parameter):

        p = p1.operator+(p2);
     

Note that changing the order of the operands of + should not change the result, but the roles of p1 and p2 change:

        p = p2 + p1;
     

is equivalent to

        p = p2.operator+(p1);  // Ok p2 and p1 are both Pair's
     


previous | start | next