Main Content

AUTOSAR C++14 Rule A13-5-3

User-defined conversion operators should not be used

Since R2021a

Description

Rule Definition

User-defined conversion operators should not be used.

Rationale

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 double
While this conversion might be expected, if you attempt to print var1 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 Implementation

Polyspace® flags all calls to conversion operators.

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 customType
{
public:
    customType(int base, int exponent): b(base), exp(exponent) { /* ...*/}
    //....
    operator double() const;
    double as_double() const {/* ...*/}

private:
    int b; //base
    int exp; //exponent
};

int func(void)
{

    customType var1(2, 5);
    double var2 = 0.5 * var1; //Non-compliant
    double var3 = 0.5 * var1.as_double(); // Compliant

    return 0;
}

In this example, the conversion of var1 to a double in the declaration of var2 uses conversion operator customType::operator double. This conversion is non-compliant because it uses a user-defined conversion operator.

The type conversion in the declaration of var3 is compliant because it uses a function to handle the conversion, and this function must be called explicitly. This ensures that the conversion is expected.

Check Information

Group: Overloading
Category: Advisory, Automated

Version History

Introduced in R2021a