TopPreprocessor commandsOperator overloading

Operator overloading

In C++ (but not in Java), one can overload operators, not just methods. We've already seen how to overload "=" in order to get a copy semantics for assignment. We can similarly overload "==", "+", and other operations.

In Java, we had to be careful of the difference between "==", which represented object identity, and equals(...), which was defined by a programmer. In C++ we can overload "==" so that we don't need that distinction. That has indeed happened with "==" in string, so we don't need to worry about what to use.

[Of course if we have

    string * a, *b;

then a == b is only true if they point to the same string (i.e. they refer to the same pointer/location), while *a == *b is true if their contents are the same.

If we wish to overload "==" for Point which has instance variables x and y then we can write

    bool Point::operator==(const Point & other) {
        return (x == other.x) && (y == other.y);
    }

We also typically overload the output function, though we do it as a non-member function as the target is an ostream, which is predefined. The idea is that we want to be able to write

    cout << pt;

Unfortunately, non-member functions like "<<" cannot access private information from a class, so we will have to be a bit tricky to get this to work.

We begin by adding a new method "print" to the Point class:

    void print(ostream & out = cout) const {
        out << "(" << x << "," << y << ")";
    }

We then add a non-member function overriding "<<"

    ostream & operator<<(ostream & out, const Point & p) {
      p.print(out);
      return out;      // why?  so that we can cascade <<
    }

We can now write code like

    cout << "p = " << p << endl;

TopPreprocessor commandsOperator overloading