Main Content

AUTOSAR C++14 Rule A13-5-2

All user-defined conversion operators shall be defined explicit

Since R2020a

Description

Rule Definition

All user-defined conversion operators shall be defined explicit.

Rationale

If you do not define a user-defined conversion operator with the explicit specifier, compilers can perform implicit and often unintended type conversions from the class type with possibly unexpected results.

The implicit conversion can occur, for instance, when a function accepts a parameter of a type different from the class type that you pass as argument. For instance, the call to func here causes an implicit conversion from type myClass to int:

class myClass {} {
  ...
  operator int() {...}
};
myClass myClassObject;

void func(int) {...}
func(myClassObject);

Polyspace Implementation

The checker flags declarations or in-class definitions of user-defined conversion operators that do not use the explicit specifier.

For instance, operator int() {} can convert variable of the current class type to an int variable both implicitly and explicitly but explicit operator int() {} can only perform explicit conversions.

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

#include <cstdint>

class MyClass {
public:
    explicit MyClass(int32_t arg): val(arg) {};
    operator int32_t() const { return val; }  //Noncompliant
    explicit operator bool() const {   //Compliant
        if (val>0) {
          return true;
        }
        return false;
     } 
private:
    int32_t val;
};

void useIntVal(int32_t);
void useBoolVal(bool);

void func() {
    MyClass MyClassObject{0};
    useIntVal(MyClassObject); 
    useBoolVal(static_cast<bool>(MyClassObject));
}

In this example, the conversion operator operator int32_t() is not defined with the explicit specifier and violates the rule. The conversion operator operator bool() is defined explicit and does not violate the rule.

When converting to a bool variable, for instance, in the call to useBoolVal, the explicit keyword in the conversion operator ensures that you have to perform an explicit conversion from the type MyClass to bool. There is no such requirement when converting to an int32_t variable. In the call to useIntVal, an implicit conversion is performed.

Check Information

Group: Overloading
Category: Required, Automated

Version History

Introduced in R2020a