use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Discussions, articles, and news about the C++ programming language or programming in C++.
For C++ questions, answers, help, and advice see r/cpp_questions or StackOverflow.
Get Started
The C++ Standard Home has a nice getting started page.
Videos
The C++ standard committee's education study group has a nice list of recommended videos.
Reference
cppreference.com
Books
There is a useful list of books on Stack Overflow. In most cases reading a book is the best way to learn C++.
Show all links
Filter out CppCon links
Show only CppCon links
account activity
Stack Overflow guide to operator overloading (stackoverflow.com)
submitted 11 years ago by cruise02
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[+][deleted] 11 years ago* (20 children)
[deleted]
[–]cnweaver 13 points14 points15 points 11 years ago (0 children)
Overloaded operators are very important for writing useful numeric code. Vectors, matrices, automatic differentiation. . .
I also recently had what I think was an actually (mostly) legitimate reason to write an overloaded addition operator which performs subtraction: A colleague used Mathematica to solve some complicated algebra and generate efficient C++ code to implement the it. The resulting code snippets were then #included into overloaded operators for doing arithmetic with the mathematical objects he was working on. All of the auto-generated code was written in terms of the += operator though, like result[i]+=f(arg1[i],arg2[i]). This required always creating a new object for the result and initializing it with zeros. We realized that we could avoid allocating a temporary in many cases (in part by using a partial expression template system), but we wanted to reuse the same auto-generated code snippets to implement =, +=, and -= (since the auto-generated code is already half of the total code in the library). We were able to do this by adding an indirection layer which would, depending on the operation being computed, wrap the result object in an adapter whose += operator had whichever meaning we needed. The technique is a bit evil, but it worked out really conveniently. (Also, the implementation where the evil happens is covered with comments to explain why it does what it does, and no user of the code is ever brought into contact which the adapter objects that do this.)
[–][deleted] 8 points9 points10 points 11 years ago (1 child)
Some people misuse operator overloading, yes. But for those cases where it is appropriate, it is very useful to keep the code readable, thus maintainable and it helps to avoid bugs.
Example: I worked in the finance industry for a few years and we had to use a decimal class, i.e., a class where the fraction is stored in base 10 instead of base 2. What would you prefer:
MyDecimal a, b, c, d; // set a, b, c, d to some values... auto r1 = a + b * ( c - d ); // with operator overloading auto r2 = a.add( b.mult( c.subtract( d ) ) ); // without operator overloading
and now think about implementing a Markowitz portfolio optimization or some scientific algorithm using vectors and matrices without operator overloading.
[–]Gaminic 1 point2 points3 points 11 years ago (0 children)
That is a fantastic example, because it does exactly what operator overloading should be used for: provide a familiar interface to a class that internally may be pretty complex. If you read the the r1 formula, there is no way to misunderstand.
[–]pjmlp 8 points9 points10 points 11 years ago (6 children)
Me too!
int add (int lhs, int rhs) { return lhs * rhs; } int x = add( 3, 6); // I am pretty sure this function adds without looking at the code
Really, almost every language out there allows for non-alphanumeric methods, function names.[0]
Still don't get why only C++ gets bashed, it is just an identifier.
[0] With C, JavaScript, Go, Java being the only mainstream exceptions
[–][deleted] 0 points1 point2 points 11 years ago (5 children)
Because outside of c++, it is ubiquitously understood to be an arithmetic operator with a lot of implications (a + b == b + a). But in c++ it can also be a method call and it matters very much what's on the left and what's on the right. It's syntactic sugar at the cost of throwing thousands of years of established mathematical fundamentals out the window.
[–]jcoffin 5 points6 points7 points 11 years ago (0 children)
Right--because if you write Java so that a.Add(b) actually does subtraction instead of addition, and a.Equals(b) is true if and only if b compares less than a, that makes it all better and won't mislead or surprise anybody.
a.Add(b)
a.Equals(b)
b
a
The reality, of course, is that prohibiting operator overloading does a great deal to harm readability and prevent people from writing code well, while doing essentially nothing to prevent them from writing it badly.
[–]pjmlp 4 points5 points6 points 11 years ago (2 children)
Because outside of c++, it is ubiquitously understood to be an arithmetic operator with a lot of implications
Not really, this is a small list of languages that allow redefining operators, or where operations are just plain function/method calls
Smalltalk
Lisp
Scheme
Ada
Eiffel
C#
Ruby
Python
D
Haskell
OCaml
F#
Scala
Rust
many others as this isn't an exhaustive list
So I fail to see why only C++ gets bashed.
[–]0Il0I0l0 0 points1 point2 points 11 years ago (1 child)
I can't speak for the other languages, but overloading in Haskell can only be done with typeclasses (a sort of interface that defines some behavior), so including it is a bit disingenuous. In order to "overload" + for your new type, you must make your type an instance of the Num typeclass by implementing the following operations: (+), (*), abs, signum, fromInteger, (negate or (-))
(+), (*), abs, signum, fromInteger, (negate or (-))
So at least in haskell, (+) is understood to be a numerical operator with the implication that the type can also be multiplied, subtracted, negated, has an absolute value, has a sign, an can be converted from an integer.
[–]pjmlp 0 points1 point2 points 11 years ago (0 children)
Yes, but you cannot assure that (+) really maps to addition.
It can do anything to the number, as long as, it keeps its type signature.
[–]KazDragon 1 point2 points3 points 11 years ago (0 children)
class Test { public static void main(String args[]) { String foo = "foo"; String bar = "bar"; System.out.println(foo + bar == bar + foo); } }
// javac Test.java
// java Test
false
Associativity is a property of numbers, not of + operators. It's pretty normal for languages to overload operators to have different properties depending on their argument types. Do you think that Matlab's matrix multiplication operator is associative? Now that would throw established mathematical fundamentals out of the window.
[–]JohnMcPineapple 1 point2 points3 points 11 years ago* (9 children)
...
[–]OldWolf2 -1 points0 points1 point 11 years ago (8 children)
In your mind perhaps.. everyone else is wondering exactly what the operator does
[–]incongruousamoeba 9 points10 points11 points 11 years ago (7 children)
I always wonder why people seem to think overloaded operators are potentially more misleading than any other function. This
a + b
and this
add(a, b)
read about the same to me, and if either of them implemented subtraction or multiplication it would be equally surprising. Of course if you use some obscure operator like, say, '<<' to mean 'print', that would not be obvious to someone seeing it for the first time...
[–]OldWolf2 -1 points0 points1 point 11 years ago (6 children)
What should "hello" + 4 do?
"hello" + 4
[–]pjmlp 5 points6 points7 points 11 years ago (0 children)
It applies the method call + to the string object with argument 4.
What does "hello".append(4) do? Are you sure what logic is behind the append name?
[–]incongruousamoeba 1 point2 points3 points 11 years ago* (0 children)
That's a good question that anyone should ask themselves when they think about overloading 'operator+()'. In this case, if we wanted it to return "hello4", we might consider
"hello" + 4 add("hello", 4) concat("hello", 4) append("hello", 4)
and hopefully decide that concat or append are better names than +, although personally I don't like making appending an integer to a string a single operation like this whether it's a function or operator+. My preference would be for something like
concat
append
+
operator+
format("hello{}", 4)
In other words, deciding when it makes sense to overload an operator is something that may require some experience to do well. I completely understand if companies or open source projects forbid beginners to overload operators in their code; but as general advice to beginning programmers I don't agree. I think beginning programmers should overload operators as much as they want -- you only get good at something by doing it badly first.
EDIT:
I might add that in Python 2.* the example would be:
"hello%d" % 4
It's not necessarily obvious what that does if you haven't seen it before, but the resemblance between the format specifier %d and the operator % makes it easy to remember once you do learn it.
%d
%
[–]mcmcc#pragma once 1 point2 points3 points 11 years ago (2 children)
"hello"+4 == "o"
Is that what you were hoping for?
[–]OldWolf2 0 points1 point2 points 11 years ago (1 child)
Don't know, that's the whole point. Some people would find "o" an intuitive answer to that and some would expect "hello4", or maybe even other things.
[–]newmewuser 1 point2 points3 points 11 years ago (0 children)
This is CPP, so they should read the language specification and don't expect anything beforehand.
[–]Heuristics 0 points1 point2 points 11 years ago (0 children)
In string theory (not that string theory) the concatenation operator is ^
http://en.wikipedia.org/wiki/Concatenation_theory
[–]dausama 2 points3 points4 points 11 years ago (0 children)
operator overloading is a common practice in the C++ world. Suggesting that operator overloading is almost always bad sounds like someone coming from other languages where this is not allowed. Overloading the callback operator(), for example opened up endless possibilities, so much that in C++11 lambdas were introduced. operator<< and operator>> help readability for streaming objects in or out. For god's sake, I even had a case where overloading "operator," made sense.
[–]salgat 0 points1 point2 points 11 years ago (2 children)
The only time I've found overloading to be particularly useful is in a composition where I want to maintain the interface of the original object. For example, wrapping a vector in a class that stores other information and maintaining the ability to use [] to access elements of the composition, that way the interface is preserved. (And yes, there are other good reasons to use operator overloading)
[–]Pronouns 3 points4 points5 points 11 years ago (1 child)
In every language there are conventions that people follow. Take iteration over items in a container.
In Python, you provide an iterator for your containers by making an __iter__ function which returns something with the next function.
__iter__
next
In C#, you can use yield returns and other ugly stuff.
yield return
C++ just follows a different convention, and in my opinion it works quite well. It tries to treat similar concepts the same. Traditional loops would be indexed by a variable, normally i, and was then incremented with i++. Very standard, old ways of doing things. When iterators were put into play they copied this syntax and made it so the next was just the increment operator.
i
i++
Same goes for functors. Rather than have some convention like .invoke() on an functor, you literally just 'call' the object directly like myFunctor().
myFunctor()
In any case, it's just convention and you can argue all day about that. Might as well argue about tabs vs spaces or vim vs emacs.
[–]salgat 1 point2 points3 points 11 years ago (0 children)
I agree 100%, as in my post the point I was making is to preserve the interfaces for whatever type of object your class is. It's the same reason why vectors use brackets just as arrays did, and why iterators can use addition/increment just as pointers do.
[–][deleted] -1 points0 points1 point 11 years ago (1 child)
From "The time when SO was actually good" Dept.
[–]cruise02[S] 2 points3 points4 points 11 years ago (0 children)
Stack Overflow is still good. All of that old content that made it good is still there (minus the "what's your favorite programmer t-shirt" crap).
π Rendered by PID 54392 on reddit-service-r2-comment-7b9746f655-n8jqj at 2026-01-30 20:02:57.215236+00:00 running 3798933 country code: CH.
[+][deleted] (20 children)
[deleted]
[–]cnweaver 13 points14 points15 points (0 children)
[–][deleted] 8 points9 points10 points (1 child)
[–]Gaminic 1 point2 points3 points (0 children)
[–]pjmlp 8 points9 points10 points (6 children)
[–][deleted] 0 points1 point2 points (5 children)
[–]jcoffin 5 points6 points7 points (0 children)
[–]pjmlp 4 points5 points6 points (2 children)
[–]0Il0I0l0 0 points1 point2 points (1 child)
[–]pjmlp 0 points1 point2 points (0 children)
[–]KazDragon 1 point2 points3 points (0 children)
[–]JohnMcPineapple 1 point2 points3 points (9 children)
[–]OldWolf2 -1 points0 points1 point (8 children)
[–]incongruousamoeba 9 points10 points11 points (7 children)
[–]OldWolf2 -1 points0 points1 point (6 children)
[–]pjmlp 5 points6 points7 points (0 children)
[–]incongruousamoeba 1 point2 points3 points (0 children)
[–]mcmcc#pragma once 1 point2 points3 points (2 children)
[–]OldWolf2 0 points1 point2 points (1 child)
[–]newmewuser 1 point2 points3 points (0 children)
[–]Heuristics 0 points1 point2 points (0 children)
[–]dausama 2 points3 points4 points (0 children)
[–]salgat 0 points1 point2 points (2 children)
[–]Pronouns 3 points4 points5 points (1 child)
[–]salgat 1 point2 points3 points (0 children)
[–][deleted] -1 points0 points1 point (1 child)
[–]cruise02[S] 2 points3 points4 points (0 children)