overloading operator && in C++

Why is it usually discouraged to overload operator && in C++?

Answer:[1] [2]

We can overload the && operator to accept two objects as follows:


bool operator &&(const Thing &, const Thing &);


However, developers will assume short circuting behavior which not work when operator overloading is enabled.

Ex:

Thing& tf1();
Thing& tf2();
if ( tf1() && tf2() ) // ...


will get translated to,

if ( operator &&(tf1(), tf2()) ) // ...


Now the functions tf1 and tf2 both will be called, and the order in which they are called is not fixed. (the arguments to a function can be evaluated in any order according to standard.) Also another problem is that short-circuting behavior of the built-in operator does not occur and is misleading to developers.

No comments: