Sign in Join
Wiki copytemporary

Operator overloading

Operator overloading refers to re-defining already defined operators with new definitions. The term is – although imprecisely – used for operator definitions, that have not yet been defined, too.

Availability

The FPC supports PXSC-style operator overloading, however it is not allowed in {$mode TP} or {$mode MacPas}. In {$mode Delphi}, operator overloading can only be done in the context of classes or advanced records (confer Delphi documentation), so the Delphi mode does not support global operator overloads as {$mode FPC} and {$mode objFPC} do.

Overloadable operators

Almost all operators can be (re-)defined:

The only operators that can not be overloaded are @ (address operator), [[^|^ (de-referencing operator)]], as and is.

Definition

An operator is declared as if it was a function, with a few differences:

operator symbol symbolic name
:= implicit
+ add, positive
- negative, subtract
* multiply
div intDivide
mod modulus
/ divide
= equal
<> notEqual
< lessThan
<= lessThanOrEqual
> greaterThan
>= greaterThanOrEqual
not logicalNot
and logicalAnd
or logicalOr
and bitwiseAnd
or bitwiseOr
xor bitwiseXor
shl leftShift
shr rightShift

Delphi compatibility operator names

Note, ><, ** and the bitwise not have no equivalent in Delphi, but the symbolic operator designation is allowed instead.

The following shows a valid operator declaration (in {$mode Delphi} the := has to be replaced by implicit and the declaration may only appear in the context of class or advanced record definitions).

delphi
operator := (x: myNewType) y: someOtherType;

Operators are defined the same way as any other function, by following the signature with a block.

Some operator overloads are not allowed:

Routing

How an operator overload definition is chosen differs in many aspects how a function is chosen.

Operator overloads should be used with caution. They potentially make it harder to identify problems, since it is not necessarily obvious that an operator overload applies.

See also


From the Free Pascal wiki, page "Operator overloading", as it stood on 2024-02-28 after a change by Alextp, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.