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:
- Why operator overloading is useful in C++
- Which operators can be overloaded
- How and when to use
friend
functions to access class members
- How to overload unary operators
- How to overload binary operators
- How to overload input and output operators
- How to overload the member pointer operator
- 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
- the member accessors.
- and ::,
- the sizeof operator, and
- the only ternary operator in C++, ?:
Among the operators that can be overloaded in C++ are these:
- arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
- bit manipulation: & | ^ << >> and &= |= ^= <<= >> = (all binary infix); ~ (unary prefix)
- boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
- memory management: new new[] delete delete[]
- implicit conversion operators
- 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.