40. Avoid providing implicit conversions

Summary

Not all change is progress: Implicit conversions can often do more damage than good. Think twice before providing implicit conversions to and from the types you define, and prefer to rely on explicit conversions (explicit constructors and named conversion functions).

Discussion

Implicit conversions have two main problems:

• They can fire in the most unexpected places.

• They don’t always mesh well with the rest of the language.

Implicitly converting constructors (constructors that can be called with one argument and are not declared explicit) interact poorly with overloading and foster invisible temporary objects that pop up all over. Conversions defined as member functions of the form operator ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.