Function Overloading
Function overloading is a feature in MQL4 that allows defining multiple functions with the same name but with different parameter lists. The compiler determines which function to call based on the arguments provided during the function call, using a signature matching algorithm.
Key Concepts
**Same Name, Different Signatures:** Overloaded functions share a name but must differ in the number of parameters, their types, or both.
**Signature Matching Algorithm:** The compiler uses a specific algorithm to select the correct overloaded function:
1. **Strict Matching:** Exact match of argument types to parameter types.
2. **Standard Type Promotion:** Automatic conversion of types (e.g.,
float to
double,
char to
int).
3. **Standard Typecasting:** Conversion between similar integer types (e.g.,
bool,
char,
uchar are single-byte;
short,
ushort are double-byte;
int,
uint,
color are 4-byte;
long,
ulong,
datetime are 8-byte).
**Ambiguity Avoidance:** The compiler cannot resolve ambiguous calls. Developers should ensure that overloaded functions have distinct signatures to avoid ambiguity. Explicit type casting is recommended when in doubt.
**System Function Overloading:** System functions can be overloaded, but care must be taken to ensure the compiler can still uniquely identify the intended function. Overloading that hides system functions (e.g., by using default parameter values that create ambiguity) is not allowed.Examples
**Valid Overloading:**
*
double AverageFromArray(const double & array[], int size);
*
double AverageFromArray(const int & array[], int size);
*
double MathMax(double a, double b, double c); (Different number of parameters)
*
double MathMax(int a, int b); (Different parameter types)
**Invalid Overloading:**
*
double MathMax(double a, double b, double c = DBL_MIN); (Hides system function due to default parameter)
*
int MathMax(double a, double b); (Same number and types of parameters as existing
double MathMax(double a, double b))
Related Concepts
[Passing Parameters](/basis/function/parameterpass)
[Operation Overloading](/basis/function/operationoverload)
[Overload (Class Methods)](/basis/oop/overload)
[Virtual Functions](/basis/oop/virtual)
[Polymorphism](/basis/oop/polymorphism)