Ad

Monday, August 13, 2007

Introduction to Operator Overloading in C++

a1 = a2 + a3;

The above operation is valid, as you know if a1, a2 and a3 are instances of in-built Data Types. But what if those are, say objects of a Class; is the operation valid?

Yes, it is, if you overload the ‘+’ Operator in the class, to which a1, a2 and a3 belong.

Operator overloading is used to give special meaning to the commonly used operators (such as +, -, * etc.) with respect to a class. By overloading operators, we can control or define how an operator should operate on data with respect to a class.

Operators are overloaded in c++ by creating operator functions either as a member or a s a Friend Function of a class. Since creating member operator functions are easier, we’ll be using that method in this article.

As I said operator functions are declared using the following general form:

  ret-type operator#(arg-list);

and then defining it as a normal member function.

Here, ret-type is commonly the name of the class itself as the operations would commonly return data (object) of that class type.

# is replaced by any valid operator such as +, -, *, /, ++, -- etc.

Now that you have understood the theory, let’s have a look at an example program:


  // Example program to illustrate
  // operator overloading
  #include <iostream.h>

  class myclass
  {
    int sub1, sub2;

  public:
    // default constructor
    myclass(){}

    // main constructor
    myclass(int x, int y){sub1=x;sub2=y;}

    // notice the declaration
    myclass operator +(myclass);

    void show(){cout<<sub1<<endl<<sub2;}
  };

  // returns data of type myclass
  myclass myclass::operator +(myclass ob)
  {
    myclass temp;

    // add the data of the object
    // that generated the call
    // with the data of the object
    // passed to it and store in temp
    temp.sub1=sub1 + ob.sub1;
    temp.sub2=sub2 + ob.sub2;

    return temp;
  }

  void main()
  {
    myclass ob1(10,90);
    myclass ob2(90,10);

    // this is valid
    ob1=ob1+ob2;

    ob1.show();
  }

At this stage many of you might be wondering why the operator function is taking only one argument when it’s operating on two objects (i.e. it’s a binary operator).

To understand this, first have a look at this line of code:

  ob1 = ob1 + ob2; 

Now assume that ‘operator+’ function is just a regular function which is called as below when the respective operator (‘+’ in this case) is encountered with respect to the objects of its class.

  ob1 = ob1.operator+(ob2);

Something like this happens internally when an overloaded operator is encountered. As you can understand from this, when an operator is encountered, the objects to the left generates a call to the operator function to which ob3 is passed, the function does the operation as defined and returns the result as an object which is then assigned to ob1.

Now I think it’s clear why a overloaded binary operator is taking only one argument.

Related Articles:

68 comments:

  1. Anonymous6:17 AM

    Thanks.. very helpful

    ReplyDelete
  2. Thank you!
    I always try to post helpful articles.

    ReplyDelete
  3. Vikesh Khanna1:33 AM

    The article on operator overloading was very helpful...espaecially the part that explained why it is necesary to have one argument in overloaded member functions.

    See if you can elaborate that a bit so that all can understand easily.

    ReplyDelete
  4. Thanks Vikesh.

    That operator function is taking one argument because it is called by the first operand, as I said:

    ob1 = ob1 + ob2;

    here the operator function of ob1 is called like below, internally:

    ob1 = ob1.operator+(ob2);

    and since any memeber function is free to access that object's data, hence the values sub1 and sub2 of the object ob1 is availabe to itself and that of ob2 is passed. Thus the called operator function has all data that is needed to complete the "+" operation.

    ReplyDelete
  5. Anonymous3:50 PM

    Hi.The explanation was good.But it would be more helpful if u eloborate it more.

    ReplyDelete
  6. rrarrr9:01 PM

    Thanks a lot for writing this ! ^^

    ReplyDelete
  7. @rrarrr

    Thanks, enjoy!

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. Ahmad Ayyub Mustofa5:27 AM

    Thank you very much for writing this. It was really helpful for me understanding.

    ob1 = ob1 + ob2

    I tought this is analogous to :

    ob1 = (ob1 +) ob2

    when you overload the operator "+", because it becomes a stand-alone function which belongs to class of ob1

    Thus it becomes :

    ob1 = ob1.operator+(ob2)

    It's like calling a function of class ob1 with ob2 as its parameter.

    ReplyDelete
  10. thanks a lot arvind,//i had been searching a lot for operator over. in books...butu provided a satisfactory explanation...thanks agn..
    AYUSH

    ReplyDelete
  11. @ Ayush,
    Thanks buddy.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Anonymous5:21 PM

    Nice work. its really helpful

    ReplyDelete
  14. Hi ayshwaryaiyer,

    Thanks!

    ReplyDelete
  15. prachi8:28 AM

    thanks a lot..!!

    ReplyDelete
  16. Hi Prachi,

    My pleasure!

    ReplyDelete
  17. thank u for gave a brief explanation about OPERATOR OVERLOADING . why we use operator overloading rather than of ordinary member functions. for example you took a two objects and add these two using operator overloading,we can do by using ordinary member functions also. what is the advantages with the usage of operator overloading rather than ordinary functions.
    THANK YOU

    ReplyDelete
  18. Ravi,

    Take a look at this line:

    a1 = a2 + a3;

    Suppose if a1, a2 and a3 are objects. Now tell me how can you add two objects by just using member function not operator overloading.

    I'll clear your doubts once you reply.

    ReplyDelete
  19. cool
    gr8 explanation

    ReplyDelete
  20. Anonymous4:54 PM

    wonderful

    ReplyDelete
  21. Hi john & Anonymous,

    Thanks!

    ReplyDelete
  22. Anonymous4:13 PM

    // returns data of type myclass
    myclass myclass::operator +(myclass ob)
    {
    myclass temp;

    // add the data of the object
    // that generated the call
    // with the data of the object
    // passed to it and store in temp
    temp.sub1=sub1 + ob.sub1;
    temp.sub2=sub2 + ob.sub2;

    return temp;
    }
    we are returning local data(temp) when it goes outside of the function it will die.when we call +operator in main we = retrn back to main it will not able to fechh any thing

    // returns data of type myclass
    const myclass myclass::operator +(myclass ob)
    {


    // add the data of the object
    // that generated the call
    // with the data of the object
    // passed to it and store in temp
    return temp(sub1 + ob.sub1,sub2 + ob.sub2);


    }

    ReplyDelete
  23. Anonymous4:15 PM

    // returns data of type myclass
    const myclass myclass::operator +(myclass ob)
    {
    // add the data of the object
    // that generated the call
    // with the data of the object
    // passed to it and store in temp
    return myclass(sub1 + ob.sub1,sub2+ob.sub2);
    }

    ReplyDelete
  24. Hi Anonymous,

    No, it's not like that.

    ...
    ...
    temp.sub2=sub2 + ob.sub2;

    return temp;
    }

    Here we're returning a copy of temp not the pointer or reference of the actual "temp" object. So it'll work fine. The actual object gets destroyed as soon as the function returns but still a copy is returned.

    Hope this answers your query.

    ReplyDelete
  25. thanks a lot you solved my problem...

    ReplyDelete
  26. Hi Hemant,

    It's my pleasure!

    ReplyDelete
  27. hiiiiiiiiii surbhi

    ReplyDelete
  28. Anonymous8:20 AM

    tanks a lot

    ReplyDelete
  29. Anonymous3:22 PM

    This comment has been removed by a blog administrator.

    ReplyDelete
  30. Anonymous5:58 PM

    This comment has been removed by a blog administrator.

    ReplyDelete
  31. Anonymous3:28 PM

    if sumbody shares his poblem , just remove d problem from ur blog if u DONT HAVE A SOLUTION

    ReplyDelete
  32. Hi Anonymous,

    "if sumbody shares his poblem , just remove d problem from ur blog if u DONT HAVE A SOLUTION"

    No one is here to write programs for others. I, like many other peoples, can only help you not work for you.

    I can help you write code but in the end it's you who has to do your work. Don't expect spoon-feeding here. You'll be shown the direction but YOU have to walk the way.

    And the comment I removed contains "give me a program for XXX" type "problem" which I have no solution for. Don't ask me to write anything for you. Try writing your own code and wherever and whenever you're having trouble, ask specific questions.

    -Arvind

    ReplyDelete
  33. I'm having trouble overloading <<.

    I keep getting an infinite loop.

    Can you direct me on how to properly overload this:

    ostream& operator<<(ostream& output, const FileController& word)
    {
    //
    output << " The word is ";
    output << word;
    return output; // for multiple << operators.
    }

    ReplyDelete
  34. Hi Mac,

    The overloading function seems okay to me. I might be able to help if you give me the whole code.

    ReplyDelete
  35. what if we dont write (myclass)in [ myclass myclass::operator +(myclass ob)]

    ReplyDelete
  36. sry i mean what if we dont write (myclass ob)in [ myclass myclass::operator +(myclass ob)]

    ReplyDelete
  37. Hi anuj,

    It's been clearly mentioned in the post itself why we need that.

    It's like asking "What if I remove the hard drive from the PC?".

    It won't work!

    ReplyDelete
  38. Thanks.... Arvind...!

    Hey, so currently what r u studying? which university? or r u working...!

    ReplyDelete
  39. Hi krishanthan,

    Check our my personal website [http://www.arvindgupta.co.in].

    BTW, thanks for your interest!

    ReplyDelete
  40. FAISAL12:57 PM

    A.O.A THIS IS VERY GOODEXAMPLE OF OPERATOR(+) LOADING

    ReplyDelete
  41. THANKS TOGIVING THE EASY EXAMPLE

    ReplyDelete
  42. Anonymous1:12 AM

    Thanks for nice example.

    Regards from Lithuania,
    algirduxx

    ReplyDelete
  43. Very Nice. Thanks for sharing ideas.


    Anand Shankar,
    Varanasi

    ReplyDelete
  44. @ WASIM, Anonymous & Anand,

    It's my pleasure!

    ReplyDelete
  45. Anonymous11:08 AM

    there is a small mistake in your content.that in the following statement ob3 was typed instead of
    ob2.
    "when an operator is encountered, the objects to the left generates a call to the operator function to which ob3 is passed,"

    ReplyDelete
  46. Anonymous2:54 PM

    Hello
    I want to about unary operator.it is a binary operator example.

    ReplyDelete
  47. Bindya1:12 PM

    Thank u so much

    ReplyDelete
  48. Anonymous12:53 PM

    Why do we have to add objects. What will be stored in obj1 for obj1=obj1+obj2;.... -By Madhav

    ReplyDelete
  49. Anonymous4:06 PM

    cooool explaination dude thanx....

    ReplyDelete
  50. Anonymous5:37 PM

    Thanks,
    It is very helpful for me.

    ReplyDelete
  51. Anonymous7:41 PM

    thanks for such a great explation

    ReplyDelete
  52. Thank you so much! You illustrate it very nicely.

    Regards,
    Tanweer from Kolkata.

    ReplyDelete
  53. would that be stack overflow.. ?? calling + operator recursively??

    ReplyDelete
  54. hi .. can u pls tell me the advantage of using operator overloading..offcourse it gives us the ability to use the operators with the class objects ,anything else than that??

    ReplyDelete
  55. PRIYA7:15 PM

    Easy and Clear.
    Thanks...

    ReplyDelete
  56. Anonymous8:21 PM

    Thank you!!

    ReplyDelete
  57. kumari3:34 PM

    Thanks for sharing ur idea

    ReplyDelete
  58. Anonymous12:18 AM

    nice but if here we take 2 argument as object then how to call

    ReplyDelete
  59. Anonymous10:35 PM

    danish ahmad khan


    i was unable to understand as to what is operator overloading meant for.........today i came to know
    thanks alot

    ReplyDelete
  60. Anonymous11:44 PM

    its very well illustrated.....

    ReplyDelete
  61. thank u
    we understand easily operator overloading

    ReplyDelete
  62. Shahid Bhat8:28 PM

    I have a small question all the main functions in C++ use int as their return type why have you mentioned it as void...Will the compiler run it successfully or generate an error message or warning

    ReplyDelete
  63. Inside the main function there is no objects created for calling the function.Why?

    ReplyDelete
  64. Anonymous11:19 AM

    thanx..alot

    ReplyDelete

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.