Operator Overloading

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

  1. Anchal Laller

    Anchal Laller New Member

    Joined:
    Feb 3, 2011
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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

    Joined:
    Feb 2, 2011
    Messages:
    51
    Likes Received:
    0
    Trophy Points:
    0
    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

    Joined:
    Dec 21, 2010
    Messages:
    41
    Likes Received:
    0
    Trophy Points:
    0
    Thanks for explaining...............
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice