Difference between revisions of "Operator overloading"

From Free Pascal wiki
Jump to navigationJump to search
(create)
 
(→‎definition: what not)
Line 49: Line 49:
  
 
Operators are defined the same way as any other function, by following the signature with a [[Block|block]].
 
Operators are defined the same way as any other function, by following the signature with a [[Block|block]].
 +
 +
Some operator overloads are not allowed:
 +
* [[User Changes 2.4.0#Overloading the assignment operator with a shortstring result|overloading <syntaxhighlight lang="pascal" enclose="none">shortstring</syntaxhighlight> assignments with lengths other than <syntaxhighlight lang="pascal" enclose="none">255</syntaxhighlight>]]
 +
* As of 2019-01-20 in the future: [[User Changes Trunk#Operator overload + no longer allowed for dynamic arrays|<syntaxhighlight lang="pascal" enclose="none">+</syntaxhighlight> in conjunction with dynamic arrays]]
 +
* <syntaxhighlight lang="pascal" enclose="none">+</syntaxhighlight> in conjunction with enumerated types
  
 
== routing ==
 
== routing ==

Revision as of 20:17, 18 January 2019

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.

overloadable operators

Almost all operators can be (re-)defined:

The only operators that can not be overloaded are as and is.

definition

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

  • Instead of the word function it starts with operator.
  • The function's identifier is always one of the available operators e.g. ><, although this would not constitute a valid identifier anywhere else.
  • The parameter list has to name exactly one or two parameters, depending on the operator.
  • A result identifier can be specified in front of the colon separating the result type, but can be omitted where the special identifier result is available.

The following shows a valid operator declaration.

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

Which operator overload definition is chose differs in many aspects how a function is chosen.

  • The assignment operator := is used for implicit typecasts.
  • Unlike regular function overloads, assignment operator overloads are chosen by their result type.
  • Operator overloads can not be chosen explicitly by their scope they are defined in. Something like unitDefiningOverloads.+ is not possible. The last operator definition always wins and this can not be changed.

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

see also