Skip to main content
GameDev.net gamedev.net
🔒 Locked

Function Overloading Question

Started by PsyberMind Dec 26, 2010 at 8:14 AM 3 replies 1.6k views
Original Post
PsyberMind
PsyberMind
I'm going through Functions in my coursework now. (Self Study on an older text book, no instructor led class)And running into a personal question that I just can't seem to answer, or maybe I have, and just don't realize it

Function overloading is the idea that functions can have the same name, as long as the parameters are different. So, for example, to draw something, you may have different methods of doing it, each would be it's own function, right?

My question is, how does the code know WHICH function to use? If I want to draw a circle, and there are 2 different ways, each in it's own function, how does the program KNOW that I want to use function A, as opposed to Function B? Is it based on the parameters that are passed?
SiCrane
SiCrane
Generally it's based on the types of the parameters used. Exact details depend on which programming language you're asking about.
PsyberMind
PsyberMind
Ack.. Sorry, thought I put that in there.. C++
Metsan
Metsan
Quote:
Original post by PsyberMind
My question is, how does the code know WHICH function to use? If I want to draw a circle, and there are 2 different ways, each in it's own function, how does the program KNOW that I want to use function A, as opposed to Function B? Is it based on the parameters that are passed?

In C++, in order to determine which version of an overloaded function to call, the compiler basically checks for the number and type of the parameters, the presence of ellipsis and the presence of const/volatile qualifiers that are not at the outermost level of a parameter type specification.
SiCrane
SiCrane
Unfortunately, exact details on how C++ does overload resolution are fairly complex. The relevant section of the C++ standard (13.3) is about 16 pages of dense text long. What basically happens is that all the possible functions for the function call are examined for the number of arguments passed. If there is more than one version that accepts the number of arguments then each parameter type then each parameter is compared to the argument types of all the overloads. Conversions for each parameter are ranked. For example, if passing an int as the first parameter to an overload with the first argument as an int is better than passing it to an overload with a first argument as a float. For one overload to be selected over another it has to have at least one better conversion sequence for one parameter and every other conversion needs to be at least as good. If even one argument is worse than it won't be selected over the other. If one overload isn't better than every other overload then the compiler gives up and tells you the overload is ambiguous.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.