▲ | jandrewrogers 5 days ago | |
A benefit of operator overloads is that you can design drop-in replacements for primitive types to which those operators apply but with stronger safety guarantees e.g. fully defining their behavior instead of leaving it up to the compiler. This wasn't possible when they were added to the language and wasn't really transparent until C++17 or so but it has grown to be a useful safety feature. | ||
▲ | tialaramex 4 days ago | parent [-] | |
However C++ offers several overloads where you don't get to provide a drop-in replacement. Take the short-circuiting boolean operators || and &&. You can overload these in C++ but you shouldn't because the overloaded versions silently lose short-circuiting. Bjarne just didn't have a nice way to write that so, it's not provided. So while the expression `foo(a) && bar(b)` won't execute function bar [when foo is "falsy"] if these functions just return an ordinary type which doesn't have the overloading, if they do enable overloading both functions are always executed then the results given to the overloading function. Edited:: Numerous tweaks because apparently I can't boolean today. |