Presentation is loading. Please wait.

Presentation is loading. Please wait.

Operator Overloading II

Similar presentations


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

1 Operator Overloading II

2 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 + - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] () -> ->* new new [] delete delete[] C++ operators that can be overloaded

3 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

4 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 << D1 << D2 << D3; ostream & operator<<(ostream &output, const Date &d) { . . . output << … // enables cascading return output; }

5 Returning modified instance using this
Preincrement operator (Date class) helpIncrement() is a facilitator method for incrementing the date returning *this returns the incremented Date for use in an expression ex: Date default; cout << ++default; will output the default date after incrementation Date &Date::operator++() { helpIncrement(); return *this; } refer to Date-OpOver2 for more examples

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


Download ppt "Operator Overloading II"

Similar presentations


Ads by Google