What does the explicit keyword mean?
What does the explicit keyword mean?
352
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023In C++, the
explicitkeyword is used to prevent implicit conversions from one type to another. For example, the following code will compile without any errors:C++
In this code, the integer
xis implicitly converted to a floaty. This is because thefloattype is considered to be "larger" than theinttype.However, if we use the
explicitkeyword, the implicit conversion will not be allowed:C++
In this code, the compiler will generate an error because the
explicitkeyword is used. This means that the conversion frominttofloatmust be explicit.The
explicitkeyword can be used with constructors, casts, and type conversion operators.Here are some examples of how the
explicitkeyword can be used:explicitkeyword can be used with constructors to prevent implicit conversions from one type to another. For example, the following code will not compile:C++
In this code, the
MyClassconstructor is declared with theexplicitkeyword. This means that the constructor cannot be called implicitly. To call the constructor, we must explicitly cast the value 10 to aMyClassobject.explicitkeyword can also be used with casts to prevent implicit conversions from one type to another. For example, the following code will not compile:C++
In this code, the
static_castoperator is used to convert the integerxto a floaty. However, because thestatic_castoperator is preceded by theexplicitkeyword, the conversion will not be allowed.explicitkeyword can also be used with type conversion operators to prevent implicit conversions from one type to another. For example, the following code will not compile:C++
In this code, the
MyClassclass has a type conversion operator that converts aMyClassobject to anint. However, because the type conversion operator is preceded by theexplicitkeyword, the conversion will not be allowed.