Function OverloadingUsually the function name tends to reflect its main purpose. As a rule, readable programs contain various well selected identifiers. Sometimes different functions are used for the same purposes. Let's consider, for example, a function that calculates the average value of an array of double precision numbers and the same function, but operating with an array of integers. Both are convenient to be called AverageFromArray:
Each function contains the message output via the Print() function;
The compiler selects a necessary function in accordance with the types of arguments and their quantity. The rule, according to which the choice is made, is called the signature matching algorithm. A signature is a list of types used in the function declaration. Example:
Function overloading is a process of creating several functions with the same name, but different parameters. This means that in overloaded variants of a function, the number of arguments and/or their type must be different. A specific function variant is selected based on the correspondence of the list of arguments when calling the function, to the list of parameters in the function declaration. When an overloaded function is called, the compiler must have an algorithm to select the appropriate function. The algorithm that performs this choice depends on castings of what types are present. The best correspondence must be unique. An overloaded function must be the best match among all the other variants for at least one argument. At the same time it must match for all other arguments not worse than other variants. Below is a matching algorithm for each argument. Algorithm of Choosing an Overloaded Function
The standard type increase is better than other standard conversions. Increase is the conversion of float to double, of bool, char, short or enum to int. Typecasting of arrays of similar integer types also belongs to typecasting. Similar types are: bool, char, uchar, since all the three types are single-byte integers; double-byte integers short and ushort; 4-byte integers int, uint, and color; long, ulong, and datetime. Of course, the strict matching is the best. To achieve such a consistency typecasting can be used. The compiler cannot cope with ambiguous situations. Therefore you should not rely on subtle differences of types and implicit conversions that make the overloaded function unclear. If you doubt, use explicit conversion to ensure strict compliance. Examples of overloaded functions in MQL4 can be seen in the example of ArrayInitialize() functions. Function overloading rules apply to overload of class methods.
Overloading of system functions is allowed, but it should be observed that the compiler is able to accurately select the necessary function. For example, we can overload the system function MathMax() in 4 different ways, but only two variants are correct. Example:
See also Overload, Virtual Functions, Polymorphism |