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?
Implicit conversions allow the compiler to treat values of a type as values of another type. There's at least one set of scenarios in which this is unambiguously bad: non-total conversions. That is, converting an A to a B when there exists A s for which this conversion is impossible.
Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
Advantages of Type Casting in CIt helps you in converting one data type to another data type. It helps in making the program lightweight. With this, you can take advantage of features like type representations and hierarchies.
Use explicit
when you would prefer a compiling error.
explicit
is 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 explicit
keyword anytime that the programmer may construct an object by mistake, thinking it may do something it is not actually doing.
Here's an example:
class MyString { public: MyString(int size) : size(size) { } //... other stuff int size; };
With the following code you are allowed to do this:
int age = 29; //... //Lots of code //... //Pretend at this point the programmer forgot the type of x and thought string str s = x;
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:
class MyString { public: explicit MyString(int size) : size(size) { } //... other stuff int size; };
Compiling errors are always better than bugs because they are immediately visible for you to correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With