Missing explicit keyword
Constructor or user-defined conversion operator missing the explicit
specifier
Description
This defect occurs when the declaration or in-class definition of a constructor or
user-defined conversion operator does not use the explicit
specifier.
The explicit
specifier prevents implicit conversion from a variable
of another type to the current class type.
The defect applies to:
One-parameter constructors.
Constructors where all but one parameters have default values.
For instance,
MyClass::MyClass(float f, bool b=true){}
.User-defined conversation operators.
For instance,
operator int() {}
converts a variable of the current class type to anint
variable.
Risk
If you do not declare a constructor or conversion operator explicit
,
compilers can perform implicit and often unintended type conversions to or from the
class type with possibly unexpected results.
The implicit conversion using a constructor can occur, for instance, when a function accepts a
parameter of the class type but you call the function with an argument of a
different type. The call to func
here causes an implicit
conversion from type int
to
myClass
:
class myClass {}{ ... myClass(int) {...} }; void func(myClass); func(0);
The reverse implicit conversion can occur when using a user-defined conversion
operator. For instance, you pass the class type as argument but the function has a
parameter of a different type. 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);
Fix
For better readability of your code and to prevent implicit conversions, in the declaration or
in-class definition of the constructor or conversion operator, place the
explicit
keyword before the constructor or operator name. You
can then detect all implicit conversions as compilation errors and convert them to
explicit conversions.
Examples
Result Information
Group: Object oriented |
Language: C++ |
Default: Off |
Command-Line Syntax: MISSING_EXPLICIT_KEYWORD |
Impact: Low |
Version History
Introduced in R2015b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)