Overloading

# Overloading Introduction

Functions and methods can be overloaded if parameter types are declared as in the following example:

int sub example(int i) {
printf("i=%d\n", i);
return i + 1;
}
string sub example(string str) {
printf("str=%s\n", str);
return str + "foo";
}
Qore::printf
string printf(string fmt,...)
Outputs the string passed to standard output, using the first argument as a format string; does not e...

In this case, the first version (`example(int)`) will be executed if called with an integer argument, and the second (`example(string)`) if called with a string argument.

Qore looks at the arguments passed to the function or method and tries to find the best match. A perfect match is when all arguments exactly match the expected types. An imperfect match is when the declared type accepts the argument value, but it is not an exact match. Examples of imperfect matches are float accepting an int value, or a number type accepting a float.

When types are declared in the source, Qore uses this information to perform overloaded function and method resolution at parse time, which speeds up runtime execution. If there is not enough information to match the function or method variant at parse time, then Qore has to perform variant resolution at runtime, therefore it's advisable to declare types whenever possible.

See also
  %require-types

# Overloaded Class Methods

Class methods may also be overloaded, but note that `destructor()`, `copy()`, methodGate(), memberGate(), and memberNotification() methods may not be overloaded, but all other methods may be overloaded.

When resolving an overloaded method in a class hierarchy, the first method that matches the arguments is selected, so even if a better match might be declared in a parent class, if any method variant matches in a class, then that class's method is used. The same rules are used with parse-time resolution as at runtime.

For calls and call references with a class prefix, when %allow-bare-refs or %new-style are in effect, static methods are searched first, then, if no match is found in the hierarchy, normal methods are searched. For calls without a class prefix, normal methods are searched first, then static methods.

See also
  Classes for more information