Explicit Specifier
Prevent C++ implicit conversion.
Introduction
In C++, the explicit keyword is used with constructors to prevent them from performing implicit conversions. Implicit means automatic. It happens without us explicitly specifying the compiler what to do. By adding the explicit
keyword before a constructor, we force the compiler not to perform any implict conversions.
Exanple
The following declarations are legal. The compiler converts the single argument to the class beging constructed.
1 | class Base { |
To prevent such implicit conversions, we can declare constructors with explicit
keyword. Thus, the previous declaration would be illegal.
1 | class Base { |
References
Explicit Specifier