Main Content

MISRA C++:2023 Rule 15.1.3

Conversion operators and constructors that are callable with a single argument shall be explicit

Since R2024b

Description

Rule Definition

Conversion operators and constructors that are callable with a single argument shall be explicit.

Rationale

Class constructors and conversion operators that are callable with a single argument of a fundamental type can be inadvertently invoked by the compiler to convert a fundamental type variable into the class. Such implicit conversion can occur in unexpected places, resulting in unexpected behavior. Declare constructors and conversion operators that are callable with a single argument of fundamental type as explicit.

Polyspace Implementation

Polyspace® reports a violation of this rule if a constructor or conversion operator satisfies all these conditions:

  • The constructor or operator has a single argument, or one argument that is not default initialized.

  • The single argument or the argument that is not default initialized has a fundamental type, such as integral types, floating point types, and void types.

  • The constructor or operator is not declared as explicit.

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

In this example, the class MyClass has a constructor that is callable with a single integer. in the function foo(), the call to func() converts the integer 5 to an object of type MyClass. Such an implicit conversion can result in unexpected results. Polyspace reports a violation.

#include <iostream>

class MyClass {
public:
	MyClass(int x) : value(x) { //Noncompliant
		std::cout << "Constructor called with value: " << value << std::endl;
	}

private:
	int value;
};

void func(MyClass obj) {
	std::cout << "Function called with MyClass object." << std::endl;
}

void foo() {
	func(5); // Implicit conversion from int to MyClass
	//...
}

Check Information

Group: Special member functions
Category: Required

Version History

Introduced in R2024b