Standard vs. User Defined Conversions in Overloaded Function Call

A non-explicit constructor taking a single argument is also a conversion operator, which casts its argument to an object of the constructor’s class. When the compiler has to resolve an overloaded function call, it takes into consideration this user-defined cast:

 class Numeric { float f;public:Numeric(float ff): f(ff) {}//constructor is also a float-to-Numeric conversion operator};void f(Numeric&); //function prototypeNumeric num(0.05); //objectf(5f);  //calls void f(Numeric&). Numeric's constructor converts argument to a Numeric object 

However, suppose we add a new overloaded version of f:

 void f (double);

Now the same function call will resolve differently:

 f(5f); //calls f(double); standard conversions have higher precedence than user-defined ones

This is because float variables are converted to double automatically in order to match an overloaded function signature. This type promotion is defined by the C++ standard. On the other hand, the conversion of float to Numeric is user-defined. User defined conversions rank lower than standard ones when the compiler has to decide which overloaded version is to be called.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: