Operator Overloading
Outline Revision What is Operator Overloading Why Operator Overloading Overloading Unary operators Overloading Binary operators Overloading Assignment operator
Revision Operator Overloading is a mechanism to redefine built-in operations for user defined types It allows to give normal C++ operators such as +,-,==,< additional meanings Operator Overloading should be used to perform the same function or similar function on class objects as the built-in behavior
Revision Operator overloading is a very neat feature of object oriented programming in C++ Each individual operator must be overloaded for use with user defined types Overloading the assignment operator and the subtraction operator does not overload the -= operator.
Things to keep in mind At least one of the operands in any overloaded operator must be a user-defined type operator + for one integer and one double, NOT possible Can only overload the operators that exist. All operators keep their current precedence and associativity, regardless of what they're used for
Operator Functions Operator functions may be defined as either member functions or as non-member functions. Non-member functions are usually made friends for performance reasons. Member functions usually use the this pointer implicitly.
Commonly Overloaded Operators Unary ++, --, (increment, decrement) Binary +, -, *, /, % (arithmetic) =, +=, -=, *=, /=, %= (assignment) ==, !=, >, <, >=, <= (relational) <<, >> (I/O) ||, && (logical) &, |, ^, ^=, &=, |= (bitwise)
Non-overloadable Operators . (dot operator / member selector) :: (scope resolution operator) ?: (conditional operator / arithematic if) .* (member pointer selector) sizeof
Overloading Unary Operator Increment Operators ( ++) Unary Operators ( --)
Example #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor { } unsigned int get_count() //return count { return count; } void operator ++ () //increment (prefix) ++count; } };
int main() { Counter c1, c2; //define and initialize cout << “\nc1=” << c1.get_count(); //display cout << “\nc2=” << c2.get_count(); ++c1; //increment c1 ++c2; //increment c2 cout << “\nc1=” << c1.get_count(); //display again cout << “\nc2=” << c2.get_count() << endl; return 0; }
Overloading Binary Operators Arithmetic Operators Assignment Operators Comparison Operators Arithmetic Assignment Operators