dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 27, 2000

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Resolution of Overloaded Functions

Let's say we have an overloaded function called fun():
 
void fun(string) { system.out.println("String"); }
void fun(int) { system.out.println("Int"); }
void fun(double) { system.out.println("Double"); }
void fun(float) { system.out.println("float"); }
If we call fun(37) how does the system choose which function to execute? Basically it chooses based on type conversions. The parameter 37 is an [int]eger and may be converted to a [double] or [float] by "widening", but cannot be converted to a [string], so fun(string) is not executed.

Choosing between the last 3 is a bit more tricky: The system will choose the type which can be most easily converted into the other two (i.e: via widening). An [int] can be widened into both [float] and [double]; A [double] can be widened into a [float] but cannot be converted to an [int]; A [float] cannot be converted to either. Thus fun(int) will be chosen.

Basically, any invocation of fun(int); can be handled by both fun(double); and fun(float);
 
Take another example:
void fun(int, double) { }
void fun(double, int) { }
And fun(1,2); is called. The system will drop an ambiguity error, since it won't know what to do here.

Understanding this mechanism is all well and fine, but it is not advisable to overload a function with types like [int] and [double] since it starts getting tricky and logical errors may start coming in.
Jeremy Chen
 
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