Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

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:

// 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

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.

Community Additions

ADD
Show:
© 2015 Microsoft