YAC++Q: Why use operator overloading

Chaotic42

Lifer
Jun 15, 2001
33,929
1,098
126
So I'm moving along in my personal C++ studies pretty well. I've written some successful code, examined other people's code, and I'm trying to start understanding why people would do certain things.

One thing I can't understand is the rationale behind operator overloading. I mean, I get what's nice about the concept: You want to be able to add two strings with
Code:
str3=str1+str2
and you might like to multiply two matrices with

It just seems to me like this is a huge invitation for failure. Even if you use sane variable names
Code:
mtrxC=mtrxA * mtrxB

It still just seems nuts. Why not write a function
Code:
mtrxC.muleq(mtrxA,mtrxB)

There's no possible confusion about what's happening there. Am I nuts? Is there something I'm not considering? It just seems... wrong.

Any thoughts?
 
Last edited:

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
I agree it's almost always better to use functions instead of operator overloading.

I could see overloading some reasonably obvious cases like = for a custom copy operator, or += to add data from another class object, but I can't remember the last time I've used overloading. Probably not this century :)
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
Back when I was teaching C++ in the 90's we considered operator overloading to be a very elegant way of making custom types behave in a seamless, natural way. But the key was to avoid altering the semantics of the operators. They had to behave in the way you would expect. In practice that meant that they got used primarily for developing language framework extensions like string classes and containers, something which developers don't have to do anymore.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
when there's no ambiguity, it improves readability. in your matrix example I would much rather do C = A * B than c.muleq(A, B) or c.set(A.mul(b)) etc. for classes encapsulating simple data types I don't see much ambiguity. of course if you start using it on complex objects then it becomes a recipe for unreadable code.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
IMO, there are essentially no good reasons to overload operators*. You always want behavior to be explicit. Operators can hide arbitrary code behind them -- that keeps me up at night.

*Exception: operator= and operator() occasionally justify an overload. The former when you must copy and there's a need to do it right (e.g., obligatory deep-copy). The latter only for interfacing with something else that uses operator(). Both very, very rarely, and you lose karma if you go ahead and do it anyway.
 

Cogman

Lifer
Sep 19, 2000
10,277
125
106
IMO, there are essentially no good reasons to overload operators*. You always want behavior to be explicit. Operators can hide arbitrary code behind them -- that keeps me up at night.

*Exception: operator= and operator() occasionally justify an overload. The former when you must copy and there's a need to do it right (e.g., obligatory deep-copy). The latter only for interfacing with something else that uses operator(). Both very, very rarely, and you lose karma if you go ahead and do it anyway.

Does C++ handle == sanely? It seems like that would be another good candidate for overloading. (I've been in java land for too long recently)

I would argue that math operators should be left alone almost always. The only case for overloading them is if you are dealing with a numeric class. Other than that, overloading things like + or += is just going to end up in confusion IMO.
 

mv2devnull

Golden Member
Apr 13, 2010
1,501
145
106
I would argue that math operators should be left alone almost always. The only case for overloading them is if you are dealing with a numeric class. Other than that, overloading things like + or += is just going to end up in confusion IMO.
Expressing math of a numeric type is a logical use case, but one should check whether any of the available numerical libraries already do provide such type (with or without the syntactic sugar), preferably with professional hardcore optimizations under their hood.

C++11 brought rvalue references, which deprecates need for expression template operator overloading.


Overload resolution can be mind-boggling even when it doesn't shoot any unaware feet.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Does C++ handle == sanely? It seems like that would be another good candidate for overloading. (I've been in java land for too long recently)

Where C++ provides a ==, it does fine. But I can't think of a non-native type for which I'd rather have == than a method called Equals().
 

Scooby Doo

Golden Member
Sep 1, 2006
1,040
18
81
Where C++ provides a ==, it does fine. But I can't think of a non-native type for which I'd rather have == than a method called Equals().

I guess it depends on it's usage...

if (string1.Equals (string2))
or
if (string1 == string2)

or

bool result = string1.Equals (string2)
or
bool result = string1 == string2

Honestly I'd take the second one for the first and the first for the latter. i.e. if (string1 == and bool result = string1.Equal....
 
Last edited:

Pia

Golden Member
Feb 28, 2008
1,563
0
0
I'm doing graphics programming, and I would hate doing all the vector and matrix math involved without operator overloading. Some parts of my code would probably double in size, and they would definitely become less readable. I'd make more semantic errors because the shape of the code would less resemble the original math in the papers whose techniques I'm implementing. I would also have more temporary variables which the compiler may not be able to optimize out.

Overloading can have value even when it doesn't exactly match some established meaning. For instance, I'm using a library where x * y on vectors is element-wise multiplication, and that's fine. There's no chance of confusing it with matrix multiplication, because the library is not a general math library, and all the vectors are column vectors, which you couldn't matrix multiply anyway. Even supposing I somehow mixed up the two, the compiler would catch it immediately because the types won't match.

Overloading = and == and < is normal. [] overloads make data structure use nicer. I can see the new "" operator overloads being useful situationally as well. Overloading << and >> is useful for extensible stream interfaces. Mathy stuff benefits from all the other overloads.

I don't see how defining math operators "hides code". The second you see one used on a class, you know it's a function call because those operators are not auto-generated for classes. It shouldn't come as a surprise to a programmer that there is code inside functions.

I have never, never, seen operator overloading cause a bug or even make the code more obfuscated, despite the hand-wringing of people coming from C or Java.
 

mv2devnull

Golden Member
Apr 13, 2010
1,501
145
106
The standard makes many things possible. Some features are really neat, if one understands them correctly. If.

The style guides emphasize safety. The assumption is that the code will be looked by someone, who does not grasp all fine details of the C++ behemoth. Sticking to "easy" subset of the language is thus the safe and practical recommendation. However, a general rule does not fit to every problem domain.
 

Cogman

Lifer
Sep 19, 2000
10,277
125
106
I'm doing graphics programming, and I would hate doing all the vector and matrix math involved without operator overloading. Some parts of my code would probably double in size, and they would definitely become less readable. I'd make more semantic errors because the shape of the code would less resemble the original math in the papers whose techniques I'm implementing. I would also have more temporary variables which the compiler may not be able to optimize out.

Overloading can have value even when it doesn't exactly match some established meaning. For instance, I'm using a library where x * y on vectors is element-wise multiplication, and that's fine. There's no chance of confusing it with matrix multiplication, because the library is not a general math library, and all the vectors are column vectors, which you couldn't matrix multiply anyway. Even supposing I somehow mixed up the two, the compiler would catch it immediately because the types won't match.

Overloading = and == and < is normal. [] overloads make data structure use nicer. I can see the new "" operator overloads being useful situationally as well. Overloading << and >> is useful for extensible stream interfaces. Mathy stuff benefits from all the other overloads.

I don't see how defining math operators "hides code". The second you see one used on a class, you know it's a function call because those operators are not auto-generated for classes. It shouldn't come as a surprise to a programmer that there is code inside functions.

I have never, never, seen operator overloading cause a bug or even make the code more obfuscated, despite the hand-wringing of people coming from C or Java.

I think it is more the thought that something might go wrong, or just something unintuitive being done with the operator. For example, Person + Hamster really doesn't make a whole lot of sense to the reader of the code but could have been done with operation overloads.

I, personally, don't see that as a good excuse to remove them. It is a bit like throwing the baby out with the bath water. As you mentioned, there are a fair number of good places for operation overloading.
 

Cogman

Lifer
Sep 19, 2000
10,277
125
106
The standard makes many things possible. Some features are really neat, if one understands them correctly. If.

The style guides emphasize safety. The assumption is that the code will be looked by someone, who does not grasp all fine details of the C++ behemoth. Sticking to "easy" subset of the language is thus the safe and practical recommendation. However, a general rule does not fit to every problem domain.

I would say the operation overloading IS part of an easy subset of C++. It is pretty easy to grasp and really cleans things up if you want to do something like using your custom object with a cout statement.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
For example, Person + Hamster really doesn't make a whole lot of sense to the reader of the code but could have been done with operation overloads.

Why not? Maybe I'm writing a science fiction-based game where some terrible genetic accident is causing humans to combine with animals. The point is, whether it makes sense is determined by the context, the types of the objects involved, and the person who defined the operator's semantics. As long as all of that is made clear I don't see the issue. Methods can hide behavior as readily as overloaded operators.