This is an old revision of the document!
Operator overloading enables defining how user-defined types behave when used with operators. In this context, the term overload means providing the definition of an operator for a specific type.
To better understand the use of operator overloading let us take an example:
struct Duration { int minute; } struct TimeOfDay { int hour; int minute; void increment(in Duration duration) { minute += duration.minute; hour += minute / 60; minute %= 60; hour %= 24; } } void main() { auto lunchTime = TimeOfDay(12, 0); lunchTime.increment(Duration(10)); }
A benefit of member functions is being able to define operations of a type alongside the member variables of that type. Despite their advantages, member functions can be seen as being limited compared to operations on fundamental types. After all, fundamental types can readily be used with operators:
int weight = 50; weight += 10; // by an operator
According to what we have seen so far, similar operations can only be achieved by member functions for user-defined types:
auto lunchTime = TimeOfDay(12, 0); lunchTime.increment(Duration(10)); // by a member function
Operator overloading enables using structs and classes with operators as well. For example, assuming that the += operator is defined for TimeOfDay , the operation above can be written in exactly the same way as with fundamental types:
lunchTime += Duration(10); // by an operator, even for a struct
Before getting to the details of operator overloading, let's first see how the line
above would be enabled for TimeOfDay . What is needed is to redefine the
increment()
member function under the special name opOpAssign(string
op) and also to specify that this definition is for the '+' character. As it will be
explained below, this definition actually corresponds to the '+=' operator:
struct TimeOfDay { // ... ref TimeOfDay opOpAssign(string op)(in Duration duration)//(1) if (op == "+") //(2) { minute += duration.minute; hour += minute / 60; minute %= 60; hour %= 24; return this; } }