Re: overloaded functions and procedures

Posted by Jenny, DelphiLand Team on May 31, 2007

In Reply to overloaded functions and procedures posted by Diane Channers P15844 on May 30, 2007

What is the exact meaning of an "overloaded" function? I've seen some Delphi functions in the Help documents described as "overloaded".
Does Delphi also have also overloaded procedures?
How can I write overloaded routines? Because this would make life a lot easier!

"Overloading" is declaring more than one routine with the same name. This feature was introduced in Delphi 4, and it's available in all Delphi versions since then (free Delphi as well as professional Delphi).

A few examples of overloaded functions that were "built-in":

Delphi 4 introduced the function Max(A, B):

function Max(A, B: integer) : this function returns a value of the type integer
function Max(A, B: Int64) : returns an Int64
function Max(A, B: Single) : returns a Single
function Max(A, B: Double) : returns a Double
function Max(A, B: Extended) : returns an Extended

Delphi 7 included the function RandomFrom(AValues):

function RandomFrom(const AValues: array of integer) : returns an integer
function RandomFrom(const AValues: array of Int64) : returns an Int64
function RandomFrom(const AValues: array of Double) : returns a Double
function RandomFrom(const AValues: array of string) : returns a string

If you declare your own overloaded routines, you must add overload; at the end of their heading. Further on, the overloaded routines must have have different lists of parameters. This means that the type of at least one parameter is different, or that the number of parameters is different.

An example:

function SumToStr(A, B: integer): string; overload;
begin
  Result := IntToStr(A + B);
end;
 
function SumToStr(A, B: real): string; overload;
begin
   Result := FloatToStr(A + B);
end; 

Here we declared two functions, both called SumToStr. When later on we use SumToStr in our code, the compiler will determine which function to use by looking at the parameters. For example, SumToStr(6, 3) calls the first function, because the parameters are of the type "integer". But SumToStr(6.5, 3.1) calls the second function, because the parameters are of the type "real".

Here is another source code example:

function SumToStr(A, B, C: integer): string; overload;
begin
  Result := IntToStr(A + B + C);
end; 

When we call SumToStr(10, 20, 30) in our code, this third function declaration is used, because the number of parameters is different from the first declaration.

Cheers!
Jenny, DelphiLand Team

Related articles

       

Follow Ups