Drawbacks of Conversion Constructors

Because the compiler can select a conversion constructor implicitly, you relinquish control over what functions are called when. If it is essential to retain full control, do not declare any constructors that take a single argument; instead, define "helper" functions to perform conversions, as in the following example:

Example

// spec1_drawbacks_of_conversion_constructors.cpp
// compile with: /EHsc
#include <stdio.h>
#include <stdlib.h>

// Declare Money class.
class Money {
public:
   Money();

   // Define conversion functions that can only be called explicitly.
   static Money Convert( char * ch ) { return Money( ch ); }
   static Money Convert( double d )    { return Money( d ); };
   void  Print() { printf_s( "%f\n", _amount ); }

private:
   Money( char *ch ) { _amount = atof( ch ); }
   Money( double d ) { _amount = d; }
   double _amount;
};

int main() {
   // Perform a conversion from type char * to type Money.
   Money Acct = Money::Convert( "57.29" );
   Acct.Print();

   // Perform a conversion from type double to type Money.
   Acct = Money::Convert( 33.29 );
   Acct.Print();
}

57.290000 33.290000

Comments

In the preceding code, the conversion constructors are private and cannot be used in type conversions. However, they can be invoked explicitly by calling the Convert functions. Because the Convert functions are static, they are accessible without referencing a particular object.

See Also

Reference

Conversion Constructors