Operator Overlading - Cmartinez-28/2143-OOP GitHub Wiki

Definition

Operator overloading is the ability to redefine/extend the behavior of existing operators, such as +,-,*,<<. It is a form of static polymorphism solved at compile-time based on the operands used.

Purpose

Operating overloading allows the user to use existing operators with their user defined classes or structs. It can be used with the friend keyword to give access to private members as a class, as well as creating a way to do arithmetic with user defined types.

Code Example

// Overloading << to give access to private members of a class
class Point
{
   int x;
   int y;
public:
   Point():x(0),y(0){}
   Point(int x,int y):x(x),y(y){} //constructors
   friend ostream& operator<<(ostream& bazooka,const Point& p) //overloading <<
   {
      return bazooka << "[" << p.x << "," << p.y << "]"; //instructions when << is used
   }                                                     //for user-defined type
//Overloading + & - for the same Point class as example above
Point operator+(const Point &rhs)
{
   return Point(x+rhs.x, y+rhs.y);
}
Point operator-(const Point &rhs)
{
   return Point(x-rhs.x, y-rhs.y);
}