Skip to content

To Overload or not to Overload

For operators here an example of assignment overloading, between real and complex numbers:

operator := (r : real) z : complex;

Notice here we assign real values (on right) to complex ones (on left): the opposite order is unknown so invalid.
And what about functions?

{Overloaded routines must be declared
 with the overload directive}

 function SumAsStr(a, b :integer): string; overload; //it can be overloaded ...
    Result := IntToStr(a + b) ;

 function SumAsStr(a, b : double): string; overload; //it can be overloaded ...
    Result := FloatToStr(a + b) ;

 function SumAsStr(a, b, c : double): string; overload; //it can be overloaded ...
    Result := FloatToStr(a + b + c) ;

As you can see these functions have the same name, and return the same type (a string), and they have to match.
All three have the overload modifier at the end of function declaration, followed by a semicolon.
You don't need our help to understand where the differences are; by a quick comparison accept respectively two integers, two doubles, three doubles (doubles are floating point numbers).
So a function overloading is possible by varying parameters in number and/or in type: we could declare another overloaded SumAsStr with 4 parameters, 3 integers and one double.

That's all here: no special effects, sorry! 🙂
All the rest relates to the code and its aim.

Now you have all coordinates to make a clever question, that is...
why can we normally sum, multiply, ect... integers with doubles, in any order?
Good: maybe because somebody has been so kindly to make us already available these common operations; in other words, basic overloading has been already done!

We have just seen a beautiful aspect in coding: the possibility give functions/procedures the same name (and eventually the same returned type) to cover the particularization of a more generic operation.
Just like a man with one face and multiple passions, here we have one interface and different inputs and behavior.
[This, a taste of Object Orient Programming which we'll start on next, goes beyond the so called Polymorphism]

Finally you must know that the modifier overload is not necessary if functions/procedures are in the same unit (the code file): they are used for compatibility with another programming environment (the Delphi, which FreePascal is affine to).
In any case it is mandatory when the functions/procedures are located in an external unit and recalled into the one in use: better, the modifier must be used in both of units.

As always, you can download the project, from here.