Home > C++ > Implicit Type Conversion

Implicit Type Conversion

Check out this bit of C++ code  and its unexpected, successful compile:

Next, observe the runtime result from the Win Visual Studio 8.0 IDE:

Thirdly, check out this bit of C++ code  and its expected, unsuccessful compile:

What’s up wit’ dat? The reason I brought this up is because we’ve discovered that we have this type of bug in our growing 5 figure code base. However, we haven’t been able to locate and kill it – yet.

Note: After being enlightened by a kind and sharing member of a linkedIn.com C++ group, I was told the reason for the successful compile. Since one of the constructors of the base class of std::string takes a char*, the 0 in the s(0) definition is implicitly converted from int(o) to char*(0); the null pointer. In the non-zero case, the compiler rejects the attempt to convert int(1) into char*(1). As this example shows, implicit type conversion, a necessary C++ language feature needed to remain backwardly compatible with C, can be a tricky and subtle source of bugs.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: