Operator Overloading

What is Operator Overloading?

Operators are the symbols (such as +, /, =, &) that perform a function. Operators are defined for Longs and Strings, but don't normally exist for user-defined types and classes. (It doesn't make much sense to do penguin3 = penguin1 + penguin2, right?) However, MBSC has ways of defining operators for UDTs and classes also. Using the same operator for multiple purposes or on multiple types is called operator overloading.

How to Overload Operators

Let's jump straight into the code. This following code snippet overloads the '=' operator for Points and uses it to compare two points. The output is "-1", meaning true.

Type Point
   Dim X as LONG
   Dim Y as LONG

   'Define the '=' operator with this function
   FUNCTION OperatorEqual(P as Point) as LONG
      OperatorEqual = X = P.X & Y = P.Y
   END FUNCTION
End Type

SUB Main(Player as LONG)
   Dim pntA as Point
   Dim pntB as Point

   pntA.x = 5
   pntA.y = 7
   pntB.x = 5
   pntB.y = 7

   PlayerMessage(Player, Str(pntA = pntB), Blue'Compare two Points and output result
END SUB

And, voilą! The "=" operator can be used for points! Operator overloading was first implemented in MBSC 2.0, about the same time as user-defined types.

The other overload functions are called: OperatorAdd (+), OperatorSubtract (-), OperatorMultiply (*), OperatorDivide (/), OperatorModulus (%), OperatorExponent (^), OperatorAnd (&), OperatorOr (|), OperatorGreaterThan (>), OperatorLessThan (<), OperatorEqualGreaterThan (>=), OperatorEqualLessThan (<=), and OperatorNotEqual (<>).

Table of Contents
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.