Operator Overloading

Operating overloading is a process where the programmer can change the operation of the normal C++ operators, such as +, *, <=, and +=. These user defined operations can then be applied to user-defined data types .

These "chameleon" operators simplify the C++ code so that a statement like d3.addobjects(d1,d2); could be changed to d3=d1 + d2;. In this example, a user defined data type in the form of objects (d1, d2, d3) has been defined. It is of a class distance.


class distance
  {
    private:
      int feet;
     float inches;

  public:
      distance( ) { feet=0; inches=0;}
      distance( int ft, float in) { feet=ft; inches=in; }
      distance operator + ( distance );
}
distance distance::operator + (distance d2)
{
    int ft = feet + d2.feet;
    float in=inches + d2.inches;
   if (in >=12)   {  in-=12;  ft++; }         // add to feet if inches >=12
  return distance(ft, in);
}
In this example the " + " operator is overloaded, allowing the addition of two objects of the same class.

Back to Object Oriented Concepts