Skip to main content

Binary operator member function one argument

Short answer

With a member function, the left operand is the calling object (passed implicitly via this pointer), so only the right operand is required as an explicit parameter. a+b becomes a.operator+(b).

Why does the overloading of a binary operator with a member function require only one argument?

A binary operator has two operands, for example a + b. When it is overloaded as a member function, the left operand is the object that calls the function, and it is passed implicitly through the this pointer. So only the right operand needs to be passed explicitly as an argument.

class Complex {
    float re, im;
public:
    Complex operator+(Complex b) {       // one argument: right operand
        Complex r;
        r.re = re + b.re;                // re  is this->re  (left operand a)
        r.im = im + b.im;
        return r;
    }
};
// c = a + b;   is interpreted as   c = a.operator+(b);

Here a is the invoking object (available as this), and b is the only explicit argument. In contrast, a friend (non-member) function has no this pointer, so it needs two arguments for a binary operator.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →