Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Aug 28, 1998

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 prototype
Numeric num(0.05); //object
f(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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date