MISRA C++:2023 Rule 16.6.1
Symmetrical operators should only be implemented as non-member functions
Since R2024b
Description
Rule Definition
Symmetrical operators should only be implemented as non-member functions.
Rationale
The MISRA C++:2023 standard advises against defining these binary operators as class members.
Arithmetic | Relational | Bitwise | Logical |
---|---|---|---|
|
|
|
|
Consider the binary operator a op b
that you define as a class
member:
class myclass{ //... myClass operator op (myClass rhs) const; };
myClass
can specify the type of only one out of the two operands.
When you call the operator, the other operand might be converted to
myClass
implicitly or explicitly. This conversion can result in a
compilation error or unexpected behavior. To avoid such inconsistent behavior, do not
define binary operators as class members.The best practice for implementing binary operators is to define them as a hidden
friend
function and then write the definition of the
friend
function with in the class. This way, the binary operator
definition can specify the type of both operand. Unintended conversion during the
operation can be prevented by using this technique. Compilers select such operators only
when both operators match the required type, which reduces unexpected errors in the
code.
Polyspace Implementation
Polyspace® reports a violation if you define any of the previously mentioned binary operators as class members.
The operators *
, +
, -
, and
&
can be both binary and unary. Polyspace does not report a violation of this rule if you define the unary version
of these operators as class members.
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
Check Information
Group: Overloading |
Category: Advisory |
Version History
Introduced in R2024b