There is a strong connection between operators and functions: both instruct the computer to perform a sequence of one or more actions. Generally, compilers recognize and process operators directly, generating the machine instructions to implement the actions. Alternatively, programmers write functions consisting of statements. The functions are either included in a language's API or are part of a specific program. C++ allows programmers to overload operators by using the operator to name a new function associated with a new class. Although programmers implement overloaded operators as functions, the operators allow an operator-and-operand syntax for calling them. Overloaded operators are controversial and disliked by some (e.g., Java's designers only overload two operators and disallow programmers to overload more).
This chapter also introduces the friend keyword to implement friend functions. Any function, not just an operator, can be a friend of a class, but C++ can only implement some significant operators as friends, so this is a natural place to introduce them. friend functions are not members of the friending class, but the class nevertheless permits them access to its private features.
Overloaded Operator Concepts
Overloaded operators
are functions with the name operator🙂 (where 🙂 is any legal operator being overloaded)
doesn't change the meaning for existing operators
doesn't alter the precedence or associativity of the operators
can't create operators that don't already exist in C++
The operator can be defined as a
class member function
friend function
Know
What are friend functions
They are not member functions, may access the private features of the friending class
They may nevertheless access the private features of an object
If the function prototype and definition are separated, the "friend" keyword goes with the prototype inside the class specification
The difference between member and non-member functions
How to overload and use operators as member functions
The number of operands
How the operands relate to the implementing function's parameters
How the implicit or "this" object relates to the operator
How to overload and use operators as friend functions
The number of operands
How the operands relate to the implementing function's parameters
That friend functions are not members of a class, so the function does not have an implicit or "this" object
How to overload << and >>
For a single class
With inheritance
With whole/part (composition and aggregation) relationships
How to define a conversion operator
How to implement an assignment operator: operator=
How to define an index operator: operator[] operator