This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 15.1.3 - Conversion operators and constructors that are callable with a single argument shall be explicit
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
This rule does not apply to copy or move constructors.
Note: this rule does not prevent the addition of explicit to other constructors.
Rationale
The explicit keyword prevents a constructor or conversion operator from being used to implicitly convert from one type to another.
Example
class C
{
public:
C( int32_t a ); // Non-compliant
};
class D
{
public:
explicit D( int32_t a ); // Compliant
D( const D & d ); // Rule does not apply - copy constructor
operator int32_t() const; // Non-compliant
explicit operator bool() const; // Compliant
};
class E
{
public:
E( int32_t a, int32_t b = 0 ); // Non-compliant - callable with one argument
E( char a = 'a', int32_t b = 0 ); // Non-compliant - callable with one argument
E( char a, char b ); // Rule does not apply - requires two arguments
};
void f( E e );
void g()
{
f( 0 ); // Implicit conversion from 0 to E
}
Copyright The MISRA Consortium Limited © 2023