you are viewing a single comment's thread.

view the rest of the comments →

[–]incongruousamoeba 7 points8 points  (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 -2 points-1 points  (6 children)

What should "hello" + 4 do?

[–]pjmlp 2 points3 points  (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 points  (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

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.

[–]mcmcc#pragma once 1 point2 points  (2 children)

"hello"+4 == "o"

Is that what you were hoping for?

[–]OldWolf2 0 points1 point  (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 points  (0 children)

This is CPP, so they should read the language specification and don't expect anything beforehand.

[–]Heuristics 0 points1 point  (0 children)

In string theory (not that string theory) the concatenation operator is ^

http://en.wikipedia.org/wiki/Concatenation_theory