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 T (where T is a type) are no betterthey interact poorly with implicit constructors and can allow all sorts of nonsensical code to compile. Examples are embarrassingly numerous (see References). We mention only two (see Examples).

In C++, a conversion sequence can include at most one user-defined conversion. However, when built-in conversions are added to the mix, the results can be extremely confusing. The solution is simple:

  • By default, write explicit on single-argument constructors (see also Item 54):

    class Widget { // …
     explicit Widget( unsigned int widgetizationFactor );
     explicit Widget( const char* name, const Widget* other = 0 );

  • Use named functions that offer conversions instead of conversion operators:

    class String { // …
     const char* as_char_pointer() const;       // in the grand c_str tradition

See also the discussion of explicit copy constructors in Item 54.

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows