OOPortal 





Operator Overloading  «Prev  Next»
Lesson 1

Introduction to Operator Overloading in C++

This module covers the fundamentals of operator overloading which is an essential part of ad hoc polymorphism.
In addition, how to build a non-native type with a consistent and complete interface will be discussed.
You will learn:
  1. Why operator overloading is useful in C++
  2. Which operators can be overloaded
  3. How and when to use friend functions to access class members
  4. How to overload unary operators
  5. How to overload binary operators
  6. How to overload input and output operators
  7. How to overload the member pointer operator
  8. How to overload the new and delete operators


You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.
Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are
  1. the member accessors.
  2. and ::,
  3. the sizeof operator, and
  4. the only ternary operator in C++, ?:
Among the operators that can be overloaded in C++ are these:
  1. arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
  2. bit manipulation: & | ^ << >> and &= |= ^= <<= >>= (all binary infix); ~ (unary prefix)
  3. boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
  4. memory management: new new[] delete delete[]
  5. implicit conversion operators
  6. miscellany: = [] -> , (all binary infix); * & (all unary prefix) () (function call, n-ary infix)
In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.