Presentation is loading. Please wait.

Presentation is loading. Please wait.

Operator Overloading I

Similar presentations


Presentation on theme: "Operator Overloading I"— Presentation transcript:

1 Operator Overloading I

2 Operator overloading C++ operators can be overloaded to perform user-defined, object- based functions Type of operators Both unary and binary Assignment Relational Input/output Subscript + - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] () -> ->* new new [] delete delete[] C++ operators that can be overloaded

3 Operator Overloading Define a method/function using the keyword operator Combine the keyword with the operator symbol to be overloaded Ex: bool operator>(int i); This will “compare” an integer to the current object Note: overloading can be defined for different types! For unary operators (!, ++), the overload method should be a member of the class For binary operators (two arguments) the overload method may be a member of the class depending on the “left-hand rule”

4 “left-hand rule” Applies to binary operators The rule:
If the object itself is on the left-hand side of the expression to be evaluated, the operator method can be made a member of the class In this case, only the right hand side of the expression need to be passed to the method, the left hand is implied (it is the class instance itself) If not, operator overloading can still be done, but it must be defined externally to the class In this case, both the left and right hand sides of the expression need to be passed to the overload function (i.e. two arguments)

5 Applying the “left-hand rule”
Left hand side is the object type Compare two Date objects bool operator>(const Date &d) { … } Single argument: the “other” Date object Left hand side is another object type Output a Date object ostream &operator<<( ostream &output, const Date &d ) { … } Two arguments: the stream and the date Example: Date-OpOver1

6 Terminology For Binary Operators:
The right-hand operand is referred to as an rvalue The left-hand operand is referred to as an lvalue

7 Friends of a class A friend of a class is an object or function that is Not a member of the class, but Is allowed access to the private members of the class anyway A friend is declared in the class definition using the keyword friend friend ostream &operator<<( ostream &, const ClassName& ); // in class definition Function is granted access to private data members Usage of friends, while allowed, is discouraged It violates the basic OOP principle of encapsulation Example: Date-Friend


Download ppt "Operator Overloading I"

Similar presentations


Ads by Google