Operator Overloading II Professor John Carelli Kutztown University






- Slides: 6
Operator Overloading II Professor John Carelli Kutztown University Computer Science Department
Operator overloading • Some operators affect the value of the current instance of an object • they need to return the modified value • For Example: • ++ • += • -- • Accomplished using the “this” variable Professor John Carelli + - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] () -> ->* new [] delete[] Kutztown University C++ operators that can be overloaded Computer Science Department
this • this is a special variable that • Is created automatically with every instance of a class • Is a pointer to that instance • i. e. its value is the memory location of the instance • It is used whenever a reference to the instance itself is needed • Enables operator “cascading” • Enables a method to return a reference to the current instance Professor John Carelli Kutztown University Computer Science Department
Cascading • Certain operators return a reference to the left-hand operand in an overloaded function • Enables operator “cascading” • Ex: // cascaded assignment A = B = C; // cascaded output cout << D 1 << D 2 << D 3; Professor John Carelli ostream & operator<<(ostream &output, const Date &d) {. . . output << … // enables cascading return output; } Kutztown University Computer Science Department
Returning modified instance using this • Preincrement operator (Date class) • help. Increment() is a facilitator method for incrementing the date • returning *this returns the incremented Date for use in an expression • ex: Date default; cout << ++default; Date &Date: : operator++() { help. Increment(); return *this; } • will output the default date after incrementation refer to Date-Op. Over 2 for more examples Professor John Carelli Kutztown University Computer Science Department
Terminology For binary operators: • The right-hand operand is referred to as an rvalue • The left-hand operand is referred to as an lvalue Professor John Carelli Kutztown University Computer Science Department






