Standard vs. User Defined Conversions in Overloaded Function Call

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.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist