170 likes | 426 Views
Operator Overloading. What is it?assigning a new meaning to a specific operator when used in the context of a specific classex. << is normally the shift left operator; but when used in conjunction with the class iostream it becomes the operator insertion; this is because the writers of the iostre
E N D
1. CS-240 C++ Operator Overloading
Dick Steflik
2. Operator Overloading What is it?
assigning a new meaning to a specific operator when used in the context of a specific class
ex. << is normally the shift left operator; but when used in conjunction with the class iostream it becomes the operator insertion; this is because the writers of the iostream class overloaded << to be insertion
cout << “some string” << endl;
remember cout is a predefined object of class iostream
in another class, << could be overloaded to mean something else
3. Operator Overloading Why do we do it?
the c++ developers felt that it made more sense to overload an operator than to come up with some name for a function than meant the same thing as the operator.
using an overloaded operator takes fewer keystrokes
many people feel that an overloaded operator is more self documenting
4. Operator Overloading Three basic ways:
as a free function (not part of a class)
as a member function
as a friend function
5. Operator Overloading
6. Overloading = as a member
7. Overloading + as a member
8. Overloading == as a free function
9. Overloading == as a member
10. Friend Functions not a member function
has access to private data
member functions work with the current (named object) friend functions work with multiple objects of the same class
tag as a friend of the class
as part of class definition identify, by prototype, each friend of the class
11. Friend Functions (cont.) Friend functions are needed in C++ due to C++’s flawed object model, Java has a better model (all objects are derived from a single object).
define the prototype in the public section of the class definition
precede the prototype with the keyword “friend”
12. Friend Functions (more) define the friend implementation in the .cpp file with the member functions
do not precede the function name with the class name and the scoping operator (ex. classname::)
13. Overloading == as a friend
14. Overloading << as a friend
15. More Overloading Thoughts = overload as a member function
== != <= >= < > overload as a member
>> << (insertion and extraction) overload as non-members (friends) returning type iostream
+-*/% (arithmetics) overload as members
+= -= ... overload same as + and -
16. Please note: The only operators that cannot be overloaded are
. (dot operator)
.* (pointer-to-member)
sizeof
?: (three operands)
17. Only existing operators can be overloaded.
new operators cannot be created (have to be made a named function member)