Operator Overloading

Let’s take it a step further. What if we literally wanted to type a < b as if our fraction were a primitive data type? We can actually do that! The boilerplate is a little bit of a hassle to remember, but you will want to memorize it because many things in the standard libraries depend on your objects being able to compare themselves. The code goes like this:

  1. #include <stdio.h>
  2. struct fraction {
  3. int numerator;
  4. int denominator;
  5. bool operator<(const fraction& second) const {
  6. if (this->numerator * second.denominator < second.numerator * this->denominator) {
  7. return 1;
  8. }
  9. return 0;
  10. }
  11. bool operator==(const fraction& second) const {
  12. if (*this < second || second < *this) {
  13. return 0;
  14. }
  15. return 1;
  16. }
  17. bool operator>(const fraction& second) const {
  18. if (second < *this) {
  19. return 1;
  20. }
  21. return 0;
  22. }
  23. };
  24. fraction fraction_new(int numerator, int denominator) {
  25. fraction f;
  26. f.numerator = numerator;
  27. f.denominator = denominator;
  28. return f;
  29. }
  30. main() {
  31. fraction a = fraction_new(1, 2);
  32. fraction b = fraction_new(3, 4);
  33. // Compare two fractions
  34. printf("a < b is %d\n", a < b);
  35. printf("a == b is %d\n", a == b);
  36. printf("a > b is %d\n", a > b);
  37. }

Success! We’ve managed to implement the basic comparison operators. Let’s try using our code with the standard library.

  1. #include <algorithm>
  2. // Copy the fraction definitions and fraction_new here
  3. main() {
  4. fraction a = fraction_new(1, 2);
  5. fraction b = fraction_new(3, 4);
  6. // Get the larger of two fractions
  7. fraction larger = std::max(a, b);
  8. printf("The larger one is %d / %d\n", larger.numerator, larger.denominator);
  9. // Sort three fractions in an array
  10. fraction arr[3] = { fraction_new(5, 6), fraction_new(3, 4), fraction_new(1, 2) };
  11. std::sort(arr, arr+3);
  12. for (int i=0; i<3; i++) {
  13. printf("%d / %d\n", arr[i].numerator, arr[i].denominator);
  14. }
  15. }

Yay it works! Interestingly, std::sort and many others in the standard library don’t need us to define anything except the operator<. Those libraries figure out == and > in the same way that we defined everything from just the less than operator. Again, make sure to memorize at least how to define the < operator so you can use the standard library with custom objects. We’ll slowly go through the custom library as we progress in our discussions of algorithms.

Going a step further, you can define almost all of the operations in C++ yourself. For example, cin defines the >> operator to store input values in variables. vector redefines the [] operator to behave like an array. Those are possible, so there’s nothing stopping you from doing the same. There’s a full list of operators you can overload in wikipedia along with "prototype examples" on what the method declarations should look like.