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 operators and can directly generate machine instructions to implement them. 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 create or overload operators by defining new functions associated with a new class. Although programmers implement overloaded operators as functions, the operators allow a special, convenient syntax for calling the functions. 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 can be a friend of a class, not just an operator, but we can only write some common and important 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
Review
How to form a function: name, return type, argument list, and body. (See Figure 2)
The difference between a function definition and a prototype. (See Figure 1)
The different syntax for defining a member function inside and outside of a class. (See Figure 8)
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=