Operator overloading in C++

To run a C++ program:

The example illustrates C++ operator overloading. Here + is defined to be applicable to a user-defined class Point.


#include <iostream>
using namespace std;

class Point {
private:
  int x, y;
public:
  Point() {
    x = 0;
    y = 0;
  }
  Point(int x, int y) {
    this -> x = x;
    this -> y = y;
  }
  int getX() {
    return x;
  }
  int getY() {
    return y;
  }
  Point operator+(Point other) {
    Point p;
    p.x = this->x + other.x;
    p.y = this->y + other.y;
    return p; // note: the resulting object will be copied
  }
}; // note: need ; after class definition

int main() {
  Point *p1 = new Point(2, 3);
  Point *p2 = new Point(5, 6);
  Point p3 = *p1 + *p2;
  cout << "x = " << p3.getX() << " y = " << p3.getY() << endl;
}


CSci 4651 course.