#2. Make all type conversions explicit

Assignments, function calls and expressions in general should not contain implicit type conversions. All type conversions should be explicit.

Type conversions should be isolated in their own line, which should consist only of the assignment of the result of the type conversion to a variable of the target type.

A statement should not mix type conversion with other operations. For example, if you need to convert an object to one of another type to pass it as a function parameter, do not do it in the function call itself; instead, do it in a separate instruction in the previous line.

Type conversion occurs when an entity of type A is, well, converted to an entity of type B. This may occur in function calls, expressions using operators, or assignments.

An explicit type conversion is one which you can read in the code. An implicit type conversion is one which does not appear in the source code, but is done automatically when the software is executed.

Making all type conversions explicit helps you identify the potentially dangerous ones. Type conversions shouldn't be spread all over your code, because good design techniques should avoid them in most cases. If you get used to always respect the types of your objects, identify the occasional type conversions and make them explicit, you will prevent some common mistakes and avoid future problems.

Bibliography

[Meyers 1998-1]
Scott Meyers: Effective C++: 50 specific ways to improve your programs and designs, 2nd Edition, Addison Wesley, 1998.

The new forms of cast are discussed in the Introduction, pages 10-11. Implicit type conversions are treated on pages 67, 83, 85 and 86.

[Meyers 1998-2]
Scott Meyers: More effective C++: 35 new ways to improve your programs and designs, Addison Wesley, 1998.

Implicit type conversions are central to the subject of Item 5: "Be wary of user-defined conversion functions", pages 24-31.

[Sutter 1999]
Herb Sutter: Exceptional C++, 47 Engineering Puzzles, Programming Problems, and Solutions, Addison Wesley, 1999.

Implicit type conversions appear on pages 19, 70, 164-165 and 191. See especially Item 39: "Automatic conversions".

Comments

Popular posts from this blog

#13. Organize your code in classes

#10. Choosing the right loop structure