Is it a bad idea to overload &&, || or comma operator and Why?
It is the abuse of operator overloading that is a bad thing. But there are also problems with operator overloading as defined in C++. Because overloaded operators are just syntactic sugar for method calls they behave just like method. On the other hand normal built-in operators do not behave like methods.
The Logical OperatorsThere are four logical operators that can be directly overloaded for a class. These are the NOT operator (!), the AND operator (&), the OR operator (|) and the exclusive OR or XOR operator (^). The short-circuit operators (&& and ||) cannot be overloaded directly.
1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed.
I wouldn't overload operator&&
or operator||
. Even if you define a class that gives rise to a Boolean algebra (finite sets, for example), it would probably be a better choice to overload operator&
and operator|
.
The reason is that C++ programmers expect special semantics for operator&&
and operator||
: they are short-circuited, i.e. don't evaluate their right-hand argument if not necessary. You can't get this behavior by overloading, since you'll be defining a function.
Overloading operator,
has been done in e.g. the Boost.Assign library. This is also the only example of its overloading that I know, and I've never even considered overloading it myself. You'd better have a very specific use case for it where no other operator is suited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With