14.10.10 overload

The overload modifier tells the compiler that this function is overloaded. It is mainly for Delphi compatibility, as in Free Pascal, all functions and procedures can be overloaded without this modifier.

There is only one case where the overload modifier is mandatory: if a function must be overloaded that resides in another unit. Both functions must be declared with the overload modifier: the overload modifier tells the compiler that it should continue looking for overloaded versions in other units.

The following example illustrates this. Take the first unit:

unit ua;  
 
interface  
 
procedure DoIt(A : String); overload;  
 
implementation  
 
procedure DoIt(A : String);  
 
begin  
  Writeln(’ua.DoIt received ’,A)  
end;  
 
end.

And a second unit, which contains an overloaded version:

unit ub;  
 
interface  
 
procedure DoIt(A : Integer); overload;  
 
implementation  
 
procedure DoIt(A : integer);  
 
begin  
  Writeln(’ub.DoIt received ’,A)  
end;  
 
end.

And the following program, which uses both units:

program uab;  
 
uses ua,ub;  
 
begin  
  DoIt(’Some string’);  
end.

When the compiler starts looking for the declaration of DoIt, it will find one in the ub unit. Without the overload directive, the compiler would give an argument mismatch error:

home: >fpc uab.pp  
uab.pp(6,21) Error: Incompatible type for arg no. 1:  
Got "Constant String", expected "SmallInt"

With the overload directive in place at both locations, the compiler knows it must continue searching for an overloaded version with matching parameter list. Note that both declarations must have the overload modifier specified; it is not enough to have the modifier in unit ub. This is to prevent unwanted overloading: the programmer who implemented the ua unit must mark the procedure as fit for overloading.