C++ Concept Map

Operator functions

Any of the normal unary or binary operators may be overloaded within a class. This allows the redefinition of an operator for use by the new type created by a class declaration. Although the body of the function can contain any code appropriate to the redefined operator, both the number of parameters (unary or binary) and the order of precedence must remain the same.

To overload an operator a function member is declared with the name operator followed by the operator symbol (operator is a reserved word in C++). e.g. in this class the operator + is overloaded to produce the effect of adding two pairs of data members:

class OPOL {
private:
   int x, y;
public:
      OPOL(int xx, int yy) : x(xx), y(yy) {}
   OPOL operator + (OPOL arg2) {
     arg2.x += x;
     arg2.y += y;
     return arg2;
   }
};

This now allows the following code to compile correctly:

OPOL a1(1, 2), a2(3, 5), a3(0, 0);
a3 = a1 + a2;

The result is that a3 contains the values x = 4 and y = 7;

The input/output classes overload the left and right shift operators (<< and >>) in order to provide insertion and extraction for streams.


Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley