Main Content

MISRA C++:2023 Rule 16.5.1

The logical AND and logical OR operators shall not be overloaded

Since R2024b

Description

Rule Definition

The logical AND and logical OR operators shall not be overloaded.

Rationale

When you overload an operator, the overloaded operator behaves as a function call. The comma operator, the logical AND (&&) operator, and the logical OR (||) operator have certain behaviors that cannot be replicated by their overloaded counterpart. While the C++ standard specifies the order of evaluation of overloaded operators, the order of evaluation of their operands is not specified. A compiler that short circuits the builtin && or || operators might not do the same for an overloaded version of these operators.

Overloading these operators creates confusion about how these operators behave. Avoid overloading the comma operator, the && operator, and the || operator.

Polyspace Implementation

Polyspace® flags the overloading of these operators:

  • Comma operator

  • && operator

  • || operator

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class flag{/**/};
class Util
{
public:
flag getValue ( );
flag setValue ( int const & );
};

bool operator && ( flag const &, flag const & ); // Noncompliant
void f2 ( Util & in3, Util & in4 )
{
in3.getValue ( ) && in4.setValue ( 0 ); // Both operands evaluated
}


In this example, the && operator is overloaded for the class flag. In f2(), the overloaded operator is used. The overloading prevent the short circuiting. The behavior of the overloaded operator might be unexpected. Polyspace flags the overloading of the && operator.

Check Information

Group: Overloading
Category: Required

Version History

Introduced in R2024b