The comparison operator can be overloaded to compare two different types or to compare two equal types that are not basic types. If the operands are not simple types, the result type of a comparison operator need not always be a boolean, but then they cannot be used in an if, repeat or while statement.
The comparison operators that can be overloaded are:
If there is no separate operator for unequal to (<>), then, to evaluate a statement that contains the unequal to operator, the compiler uses the equal to operator (=), and negates the result. The opposite is not true: if no ”equal to” but an ”unequal to” operator exists, the compiler will not use it to evaluate an expression containing the equal (=) operator.
As an example, the following operator allows to compare two complex numbers:
the above definition allows comparisons of the following form:
The comparison operator definition needs 2 parameters, with the types that the operator is meant to compare. Here also, the compiler doesn’t apply commutativity: if the two types are different, then it is necessary to define 2 comparison operators.
In the case of complex numbers, it is, for instance necessary to define 2 comparisons: one with the complex type first, and one with the real type first.
Given the definitions
the following two comparisons are possible:
Note that the order of the real and complex type in the two comparisons is reversed.
The following example shows that the result type does not need to be a boolean:
When executed, this example will print
obviously, a statement as
Will not compile, since the if statement needs a boolean check: