I understand that the keyword explicit can be used to prevent implicit conversion.
For example
Foo {
public:
explicit Foo(int i) {}
}
My question is, under what condition, implicit conversion should be prohibited? Why implicit conversion is harmful?
Use
explicitwhen you would prefer a compiling error.explicitis only applicable when there is one parameter in your constructor (or many where the first is the only one without a default value).You would want to use the
explicitkeyword anytime that the programmer may construct an object by mistake, thinking it may do something it is not actually doing.Here’s an example:
With the following code you are allowed to do this:
But the caller probably meant to store “3” inside the MyString variable and not 3. It is better to get a compiling error so the user can call itoa or some other conversion function on the x variable first.
The new code that will produce a compiling error for the above code:
Compiling errors are always better than bugs because they are immediately visible for you to correct.