9.3 Record operators

Operator overloading is treated in detail in the chapter on operator overloading chapter 15, page 871. However, since Delphi implemented operator overloading as part of advanced records, a few words need to be said about it here.

As can be seen in the syntax diagram for extended records, FPC supports the Delphi syntax for operators on extended records. This syntax is available in both ObjFPC and Delphi mode.

In objfpc mode, the operators must be defined with their symbolic names, just as regular operator overloads:

{$mode objfpc}
{$modeswitch advancedrecords}

Type
  TComplex = record
    Re,Im : Double;
    class operator +(a,b : TComplex) : TComplex;
  end;

class operator TComplex.+ (a,b : TComplex) : TComplex;
begin
  Result.re:=A.re+B.re;
  Result.im:=A.im+B.im;
end;

The operators work just as they would if they were defined using the regular FPC syntax for operators, but this syntax is of course limited to record types. Note that they have the class keyword prefixed, and have the record type name prepended in the implementation.

As indicated above, in ObjFPC mode, the operators must be indicated with their symbol names. By contrast, in Delphi mode, the names of the operators can also be used, similar to the syntax in Delphi:

{$mode delphi}
Type
  TComplex = record
    Re,Im : Double;
    class operator add(a,b : TComplex) : TComplex;
  end;

class operator TComplex.add (a,b : TComplex) : TComplex;
begin
  Result.re:=A.re+B.re;
  Result.im:=A.im+B.im;
end;

This is of course because the syntax must be compatible with Delphi.

Below is a table that links the symbolic operator names to the plain-text name. Note that some FPC operators do not have an equivalent usin a Delphi name.


Table 9.1: Operator names

Symbol Name


+ add or positive
- subtract or negative
* multiply
/ divide
** (no equivalent)
>< (no equivalent)
= equal
< lessthan
<= lessthanorequal
> greaterthan
>= greaterthanorequal
<> notequal
:= implicit
in in
shr rightshift
shl leftshift
div intdivide
mod modulus
and bitwiseand or logicaland
or bitwiseor or logicalor
xor bitwisexor
not logicalnot

For example, the power operator (**) can be used in Delphi mode using its symbolic name:

{$mode delphi}
{$modeswitch advancedrecords}

Type
  TComplex = record
    Re,Im : Double;
    class operator **(a,b : TComplex) : TComplex;
  end;

class operator TComplex.** (a,b : TComplex) : TComplex;
begin
  Result.re:=-B.re;
  Result.im:=-B.im;
end;

Var
  a,b : TComplex;
begin
  a:=a**b;
end.

More information on operator overloading can be found in the chapter on operator overloading chapter 15, page 871.