Drawbacks of Conversion Constructors
Visual Studio 2005
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:
// 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();
}
Output
57.290000 33.290000