Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why implicit conversion is harmful in C++

Tags:

c++

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?

like image 992
skydoor Avatar asked Feb 27 '10 03:02

skydoor


People also ask

Is implicit type conversion bad?

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.

Does C allow implicit conversion?

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.

What happens in implicit conversion?

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.

What are the advantages of type conversion in C?

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.


1 Answers

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.

like image 78
Brian R. Bondy Avatar answered Oct 11 '22 13:10

Brian R. Bondy