C++: Member Overloading Binary Operators which Modify the Left Operand eg +=

Viewed 49

I'm learning about Operator Overloading at the moment on learncpp.com and came across a statement that I can't quite wrap my head around. Here it is:

When dealing with binary operators that do modify the left operand (e.g. operator+=), the member function version is typically preferred. In these cases, the leftmost operand will always be a class type, and having the object being modified become the one pointed to by *this is natural. Because the rightmost operand becomes an explicit parameter, there’s no confusion over who is getting modified and who is getting evaluated.

I don't understand why the left hand operand will always be a class type. If I were overloading +=, for example, why couldn't I overload with the user defined class as the righthand parameter, like below?

void operator+=(int blah, MyNewClass foo);

Thanks in advance!

1 Answers

Despite the comments, you read this correctly: it’s talking about all such modifying operators, and it’s using the statement about the left-hand operand to justify the idea of a member function being “typically preferred”. (If it’s going to be a class-type object, you definitely have the opportunity to use a member function, and we generally prefer to express modifications to such objects in terms of member functions.)

The passage simply doesn’t consider the esoteric possibilities of overloading with non-member functions:

enum nil {};
// Use left-to-right compound assignment:
void operator+=(const int &i,nil &n)
{n=static_cast<nil>(n+i);}
// Make something into a pointer (*):
template<class T>
void* operator*=(T &t,nil) {return &t;}

struct A {operator int();};
// Convert sum to a percentage (%):
double operator%=(A a,A b) {return (a+b)/100.;}
// Infix call notation (like $ in Haskell):
template<class R>
R operator&=(R f(int),A a) {return f(a);}

Very occasionally someone might find a clever way of using, say, >>= in this fashion to emulate Haskell, but for someone just learning the language (to whom that passage is certainly addressed), perhaps the very possibility of such examples is best left unsaid. (Forget I said anything.)

Related