Hacker News new | ask | show | jobs
by simias 2209 days ago
It might be a bit extreme but the more I'm exposed to operator overloading the more I think that it's a bad idea 99% of the time.

The only use that seems absolutely in my opinion is when the overload is absolutely transparent mathematically, for instance to implement geometrical transformations on a Matrix class.

That works because in this case you don't actually end up with "custom" behavior, you just expand the standard and well understood notation of the language by plugging the standard and well understood mathematical notation for matrix operations. Anybody who understands this mathematical notation will be able to understand what the code does without additional context.

Anything beyond that is just asking for trouble IMO. It's basically code obfuscation.

Of course C++ has precedent for that sort of insanity, especially with the IMO absolutely bonkers use of the bit shift operators for... input/output processing. A notation that you'll note hasn't had a lot of success outside of C++.

4 comments

> It might be a bit extreme but the more I'm exposed to operator overloading the more I think that it's a bad idea 99% of the time.

Quite a moderate position in practice. There are a substantial number of programmers who enjoy being able to tell what basic syntax does from memory without having to cross-reference documentation and source files.

And as you allude to, the example in question isn't a sum; it is an append. It would be far more appropriate to have an a = append(a, {1,2,3,4,5}) style construct. Or something with pointers if efficiency is important. Or construct the vector inline in older versions of C++. The += should be reserved for actual vector summing.

This whole article stands as a reminder that C++ is a remarkable language, and is starting to make up a lot of ground on achieving feature parity with Common Lisp.

I would add string + and += operators to list but that is it really.
That is pretty extreme. Where would we be without assignment and comparison overloads? Or dereference?
iostream hasn't had a lot of success inside C++ either. Operator overloading is one of those features that you wish for when you don't have it. Besides standard math operators, assignment also ends up playing a major role in making data structures behave well when managing resources.

It can be abused but most of the time is extremely convenient. Iostream and boost set a terrible example however. Boost especially goes into the deep end on templates, operators, crazy dependencies, unacceptable compile times etc. It really isn't fair to judge modern C++ on boost. Instead of being batteries included, boost is now more a last resort.