Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading logical operators considered bad practice?

Is it a bad idea to overload &&, || or comma operator and Why?

like image 457
cpx Avatar asked Feb 27 '11 12:02

cpx


People also ask

Is operator overloading bad practice?

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.

Can logical operators be overloaded?

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.

What are the limitations of operator overloading?

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.


1 Answers

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.

like image 108
Fred Foo Avatar answered Sep 20 '22 02:09

Fred Foo