Main Content

MISRA C++:2008 Rule 5-2-11

The comma operator, && operator and the || operator shall not be overloaded

Description

Rule Definition

The comma operator, && operator and the || operator shall not be overloaded.

Rationale

When you overload an operator, the overloaded operator behaves as a function call. The comma operator, the && operator, and the || operator have certain behaviors that cannot be replicated by their overloaded counterpart. For instance, a compiler might short circuit the builtin && or || operators. But such short circuiting is not possible when you use 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: Expressions
Category: Required

Version History

Introduced in R2013b