User-defined conversion operators should not be used
User-defined conversion operators should not be used.
User-defined conversion operators might be called when you neither want nor expect them
to be called, which can result in unexpected type conversation errors. For instance, in this
code snippet, the user-defined conversion operator converts type
customType to double to allow mixed mode
expressions:
class customType
{
public:
customType(int base, int exponent);
//....
operator double() const; // Conversion operator, convert customType to double
};
customType var1(2,5);
double var2 = 0.5 * var1; //Conversion operator called, converts var1 to doublevar1 by using
cout << var1; without defining operator
<< for customType objects, the compiler uses the
conversion operator to implicitly convert and print var1 as a
double. To avoid these unexpected conversions, replace the conversion operator with an
equivalent function. The function must then be called explicitly. If you cannot avoid using
conversion operators in your application, see rule AUTOSAR C++14 Rule
A13-5-2.
Polyspace® flags all calls to conversion operators.
If you expect a rule violation but do not see it, refer to Coding Standard Violations Not Displayed.
| Group: Overloading |
| Category: Advisory, Automated |