For the compiler to understand what code to generate from a + b or a == b, it needs a rule that tells it what it means to add or compare the two values. For basic types, like int or double, the compiler already knows how to add them. But for user-defined types, like Point, there will be no such rules. So the compiler would refuse to compile something like:
Point a(1, 2);
Point b(1, 2);
if (a == b) // error: no rule for Point == Point
To fix this, we can define an operator overload for + or == that tells the compiler what to do when it sees the operator used with two Points. For the == operator, we would define a function that compares both the x and y coordinates of the two Points and returns true if they are equal, or false otherwise. Given that rule, the compiler would then know what to do with a == b. This is called operator overloading.
Before we look at the syntax for operator overloading, there are some limitations to be aware of:
You cannot define your own operator symbols. So you can not make ** for exponentiation or %% for percent because those symbols are not already operators.
In addition to those technical limitations, there are some conventions we should stick to so that our code is easy to understand. Most importantly, we want to make sure that operator overloads we define are consistent with how that operator works for built-in types. In other words, if we define + for a data type, the operation it performs should be βadditionβ. Defining a + for a Fraction class that added two fractions would be intuitive. Anyone who saw fraction1 + fraction2 would expect it to add the two fractions together. On the other hand, what would + mean for a Person class? person1 + person2 does not have a clear meaning. So we shouldnβt define an operator overload for + for Persons that does something like make them friends or set them as spouses.