Delphi: Operator Overloading

Delphi has the ability to include operator overloading for structured types, this allows you to use any standard operator on your structured type. The Delphi documentation on the subject states that you can apply operator overloading to both structured types and classes, however this is wrong, it can only be applied to structured types. Here’s an example of it being used:

program OperatorsTest;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TIntValue = record
  private
    FValue: Integer;
  public
    class operator Add(const a, b: TIntValue): TIntValue;
    class operator Implicit(const a: Integer): TIntValue;
    class operator Implicit(const a: TIntValue): Integer;
    property Value: Integer read FValue;
  end;

{ TIntValue }

class operator TIntValue.Add(const a, b: TIntValue): TIntValue;
begin
  Result.FValue := a.FValue + b.FValue;
end;

class operator TIntValue.Implicit(const a: Integer): TIntValue;
begin
  Result.FValue := a;
end;

class operator TIntValue.Implicit(const a: TIntValue): Integer;
begin
  Result := a.FValue;
end;

var
  Int: TIntValue;

begin
  Int := 5;
  Int := Int + 10;
  WriteLn(IntToStr(Int));
  Readln; // Prevent window from closing
end.

The documentation shows you all of the operators you can overload and has some extra examples as well.

Read More