Skip to content

To Overload or not to Overload

And here the code:

unit Unit1; 

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
  StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end; 

var
  Form1: TForm1;

implementation

{Overloaded routines must be declared
 with the overload directive}

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

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

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

 {

 OVERLOAD IN LAZARUS

 Prior to version 1.9 of the compiler,the overloaded functions needed to be in the same unit.
 Now the compiler will continue searching in other units if it doesn’t find a matching version
 of an overloaded function in one unit, and if the overload keyword is present.

 If the overload keyword is not present,then all overloaded versions must reside in the
 same unit,and if it concerns methods part of a class, they must be in the same class,
 i.e. the compiler will not look for overloaded methods in parent classes if the overload
 keyword was not specified.

 ***GENERALLY OVERLOAD IS USED ON THE SAME CLASS***

 }

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
begin
 Label1.Caption := SumAsStr(1,2);
 Label2.Caption := SumAsStr(1.1,2.2);
 Label3.Caption := SumAsStr(1.1,2.2,3.3);
end;

initialization
  {$I unit1.lrs}

end.

It's very simple, isn't it?

That's all for now.

Next time, Object Oriented Programming!

Have fun, see you!