re: An Introduction to Overloading Operators (for Beginners by a Beginner) VIEW POST


Very good explanation.

Something further that will probably be worth adding, however...

Overloaded binary operators, like +, declared within your class will assume an object of that class's type is the left hand operand.

This gets to be very very important information when you consider using overloaded operators to allow adding an int to your ComplexNumber class. If you have this in your class...

ComplexNumber& operator+(int rhs) const {...}

Then you can do this...

//foo is a ComplexNumber
foo = foo + 6;

However, you cannot do this...

foo = 6 + foo;

This throws a lot of C++ beginners for a loop, because they naturally assume that the commutative property of + is assumed. (Worse, your end users will curse you for breaking the rules of math.)

Thus, you actually have to declare a second overloaded operator outside your class...

ComplexNumber& operator+(int lhs, ComplexNumber& rhs) {...}

If you've declared both of those overloaded operator functions, the commutative property is preserved.

foo = foo + 6;
foo = 6 + foo;

As a rule, you should always declare binary operators for differing operand types both ways, even for non-commutative operands like least, unless there's some illogic with one of the arrangements. If 42 + foo works, then 42 - foo should as well, right?

It is for this reason we conventionally use the names lhs and rhs for our overloaded operator arguments. lhs means "left-hand side", and rhs means "right-hand side". This helps prevent confusion. You should always use these names for operator arguments, unless you have a very VERY VERY good reason to use some other names. In fact, I'd even say that if you think you have a good reason, I'd bet you fifty bucks you're mistaken. ;)

One other tip: we virtually always declare an external overloaded operator function as friend of the class it relates to. There are exceptions, but make it your automatic habit.


Thank you so much for pointing this out! I learned a lot from your comment. Will definitely take down notes here.

code of conduct - report abuse