5 ms·
> That't literally the only place where operator overloading makes any sense. That may be true for C++ (I'll take your word for it), but not for all programmin
by doodpants 3y ago
> That't literally the only place where operator overloading makes any sense.
That may be true for C++ (I'll take your word for it), but not for all programming languages in general. For example, in C# it's fairly common to overload == and != to implement value equality for reference types (classes).
Of course, you should really only do this for immutable classes that are mostly just records of plain old data. And C# 9 introduced record classes, which is a more convenient way of defining such classes. But record classes still overload these operators themselves, so you don't have to do it manually.
- throwaway894345 3y agoHonestly that sort of thing always confused me when I worked in Java, C#, etc. I could never tell at a glance whether the operator was doing an identity comparison or a value comparison, and I definitely contributed a few bugs from this misunderstanding. In Go which lacks operator overloading, we either `ptr1 == ptr2` or we do some `ptr1.Equals(ptr2)` for value comparisons and `ptr1 == ptr2` for pointer comparisons--in either case, there is no ambiguity and IME fewer bugs.
- wizofaus 3y agoJava's the same regarding == and .equals( ) and when it's Java code written by devs who also work in other languages, it definitely still results in bugs, sometimes that go undiscovered for remarkably long times (particularly if == happens to return the right result in most cases). Meaning/needing to compare references for string (and similar) types is exceedingly uncommon, yet uses the more "natural" syntax for testing equality. FWIW I can't remember working with a codebase where unexpected behavior due to operator overloading was a serious problem.
- gpderetta 3y agoThat's more of a problem with languages that confuse value types and references.