Skip to main content

Section 20.2 Guidelines

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.
  • You cannot change the order of operations of the symbols. So in a + b * c, the * must come first regardless of the type of data.
  • You cannot change how the operators work for existing types. Thus you can’t make + mean something new for ints.
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.

Checkpoint 20.2.1.

Mark the true statements about operator overloading
  • Given a Point class, you could define a new operator ^^^ that performs a custom operation.
  • Built in types (int, double) already have operator definitions.
  • Given a Point class you could make a + operator that returned the distance between two points.
  • Correct - that is possible. But just because you can does not mean you should. It is not clear that p1 + p2 should produce the distance.
  • Given a Point class you could make an == operator to decide if two points had the same coordinates.
  • You can redefine how the operators work for built in types.
You have attempted of activities on this page.