1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Operator Overloading

Discussion in 'C++' started by Anchal Laller, Feb 3, 2011.

  1. Anchal Laller

    Anchal Laller New 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??
     
  2. kumarmannu

    kumarmannu 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 a moderator: Feb 3, 2011
  3. aishaarora

    aishaarora Banned

    Thanks for explaining...............
     

Share This Page