Main Content

MISRA C++:2008 Rule 12-1-3

All constructors that are callable with a single argument of fundamental type shall be declared explicit

Description

Rule Definition

All constructors that are callable with a single argument of fundamental type shall be declared explicit.

Rationale

Class constructors 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 that are callable with a single argument of fundamental type as explicit.

Polyspace Implementation

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

  • The constructor 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 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 R2013b