Operator Overloading

Anchal Laller's Avatar, Join Date: Feb 2011
Newbie Member
Why <<(),>>() are used as insertion operator and extraction operator, why dnt we use function instead???
What is the cost of using Overloaded operators??
What is the efficient and technical differences in using overloaded operators and functions to perform the same task??
kumarmannu's Avatar
Banned
In computer programming, operator overloading (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments. Sometimes the overloadings are defined by the language; sometimes the programmer can implement support for new types.
In this case, the addition operator is overloaded to allow addition on a user-defined type "Time" (in C++):
Code:
 Time operator+(const Time& lhs, const Time& rhs) {
     Time temp = lhs;
     temp.seconds += rhs.seconds;
     if (temp.seconds >= 60) {
         temp.seconds -= 60;
         temp.minutes++;
         }
     temp.minutes += rhs.minutes;
     if (temp.minutes >= 60) {
         temp.minutes -= 60;
         temp.hours++;
         }
     temp.hours += rhs.hours;
     return temp;
     }
Addition is a binary operation, which means it has left and right operands. In C++, the arguments being passed are the operands, and the temp object is the returned value.

The operation could also be defined as a class method, replacing lhs by the hidden this argument; however this forces the left operand to be of type Time and supposes this to be a potentially modifiable
Code:
Time Time::operator+(const Time& rhs) const {
     Time temp = *this;  /* Copy 'this' which is not to be modified */
     temp.seconds += rhs.seconds;
     if (temp.seconds >= 60) {
         temp.seconds -= 60;
         temp.minutes++;
         }
     temp.minutes += rhs.minutes;
     if (temp.minutes >= 60) {
         temp.minutes -= 60;
         temp.hours++;
         }
     temp.hours += rhs.hours;
     return temp;
     }

Last edited by shabbir; 3Feb2011 at 14:56.. Reason: Code blocks
aishaarora's Avatar
Banned
Thanks for explaining...............