CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 26
  1. #1
    Join Date
    Jan 2006
    Location
    Visby, SWEDEN
    Posts
    78

    Overloading an operator... I'm really not getting it.

    I hope I won't get flamed for this, but after 2 books "Small C++" by Deitel & Deitel, "C++ for java programmers" - Mark Weiss and 2 tutorials on the net, I still don't understand the syntaxes for overloading an operator and how to use them..
    Code:
    ostream &operator<<( ostream &output, const PhoneNumber &number )
    {
       output << "(" << number.areaCode << ") "
    	  << number.exchange << "-" << number.line;
       return output;
    Code:
    Fraction operator+(const Fraction &rhs)
    	{
    		Fraction temp;
    		temp.den = this->den * rhs.den;
    		temp.num = rhs.den * this->num +
    			this->den * rhs.num;
    		return temp;
    	}
    Aha! This says very much to me..
    Code:
       bool operaotr==(const Card& rhs) const
       {
          return suit == rhs.suit && value == rhs.value;
       }
    
    Card aceSpades(Card::spade, 1);
    what's with the &rhs's everywhere? Is aceSpades line supposed to have something to do with the overloading?

    I've looked around some more on the net and all they do is take examples from a physisist's physics calculating class or something and spew code all over and then they say: "See? That wasn't so hard", and I'm like, what the hell happened here? What is what?

    There is no place where they explain step by step how to initiate it and then use it....
    Last edited by dreamfluid; January 29th, 2006 at 07:56 AM.
    "The best ideas aren't better than the worst, if you don't do anything about it."
    So I guess that's why I'm here... Now I just hope it's a good one.


  2. #2
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,244

    Re: Overloading an operator... I'm really not getting it.

    [ Moved thread ]
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading an operator... I'm really not getting it.

    You could take a look at an FAQ concerning operator overloading.

    rhs presumably stands for "right hand side", and so refers to the value on the right hand side of a dyadic operator.

    Is aceSpades line supposed to have something to do with the overloading?
    Probably not, it looks like it is meant to instantiate a Card object.

  4. #4
    Join Date
    Oct 2005
    Location
    England
    Posts
    803

    Re: Overloading an operator... I'm really not getting it.

    Quote Originally Posted by laserlight
    You could take a look at an FAQ concerning operator overloading.

    rhs presumably stands for "right hand side", and so refers to the value on the right hand side of a dyadic operator.


    Probably not, it looks like it is meant to instantiate a Card object.

    it does stand for right hand side , well thats the convension that i use. Below is a hopefully easy examply.

    Code:
    #include <iostream>
    
    using namespace std;
    
    class Counter
    {
        public:
            Counter();
            Counter(int initialValue);
            ~Counter(){};
            int GetItsVal() const {return itsVal;}
            void SetItsVal(int x) {itsVal = x;}
            Counter operator+ (const Counter &);
            
        private:
            int itsVal;
            
    };
    
    Counter::Counter(int initialValue):itsVal(initialValue)
    {}
    
    Counter::Counter():itsVal(0)
    {}
    
    Counter Counter::operator+(const Counter & rhs)
    {
        return Counter(itsVal + rhs.GetItsVal());
    }
    
    int main()
    {
    
        Counter varOne(2),varTwo(4),varThree;
        varThree = varOne + varTwo;
        
        cout << "varOne: " << varOne.GetItsVal()  << endl;
        cout << "varTwo: " << varTwo.GetItsVal()  << endl;
        cout << "varThree: " << varThree.GetItsVal() << endl;
        
        system("PAUSE");
        return 0;
        
    }
    The overloaded + operator enables you to add the objects together. when the + operator is used it passes in the counter variable on the right and adds it to the counter object which is calling the function. The &rhs means it is passed by reference. I always think of it as a member function called "+" so nomally you would do functionName(params), but this time its +(params) without the parenthisis.

    In the case of your code it tells the object what to do when two objects are compared. It returns true if they are equal and false if they are not.

    Rich

  5. #5
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Overloading an operator... I'm really not getting it.

    Let's try to bring some order in this:
    Quote Originally Posted by dreamfluid
    Code:
    ostream &operator<<( ostream &output, const PhoneNumber &number )
    {
       output << "(" << number.areaCode << ") "
    	  << number.exchange << "-" << number.line;
       return output;
    Code:
    Fraction operator+(const Fraction &rhs)
    	{
    		Fraction temp;
    		temp.den = this->den * rhs.den;
    		temp.num = rhs.den * this->num +
    			this->den * rhs.num;
    		return temp;
    	}
    These examples you quote there are quite different. The first one overloads the operator <<, making it possible to print out an object of class PhoneNumber. The second one deals with the operator + for two objects of type Fraction.
    What makes these examples difference, is that the second one is a member function of class Fraction, while the first one is not a member function. That's why the first example takes two arguments (i.e. in the statement "cout << number;", cout would be the first and number the second argument), while the second example takes only one argument (i.e. in the statement "a+b;" a would be the object for which the function is called (the left hand side (lhs)) and be would be the argument (the right hand side (rhs)).

    Before overloading operators, it is good to know what you want to achieve. One of the simplest examples is that you are writing a class, where you want to make objects comparable by using the operators ==, != and maybe <, >. So let's use the card example:
    Code:
    enum Suite {Clubs, Spade, Heart, Diamond};
    
    class Card
    {
    private:
      Suite suite;
      int value;
    public:
      Card( Suite s, int v ) : suite( s ), value( v ) {};
      bool operator==( const Card& rhs ) { return rhs.suite==suite && rhs.value==value; };
      bool operator!=( const Card& rhs ) { return rhs.suite!=suite || rhs.value!=value; };
    };
    The class definition defines a class Card. Objects of the class have a suite and a value, e.g Spade and 7.
    The class defines the operator== and !=, so now it is easy for code using objects of class Card to compare two such objects. In the example below:
    Code:
    Card S7(Spade, 7);
    Card H7(Heart, 7);
    If (S7 == H7 ) { // the cards are the same...
    The operator is used. More precisely, the operator is use on the object S7, and H7 is passed as argument. In other words, the if statement could be written as
    Code:
    if (S7.operator==( H7 )) { // ...
    The function definition simply defines, when two cards are equal, i.e. if they have equal suite and equal value.

  6. #6
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Overloading an operator... I'm really not getting it.

    but here operator+ is defined wrong as I so often see it.

  7. #7
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading an operator... I'm really not getting it.

    but here operator+ is defined wrong as I so often see it.
    hmm... yes, I would think so too. Perhaps defining operator+= as a member than defining a global operator+ in terms of the operator+= would be better?
    Code:
    void Counter::operator+=(const Counter& rhs)
    {
    	itsVal += rhs.itsVal;
    }
    
    Counter operator+(Counter lhs, const Counter& rhs)
    {
    	lhs += rhs;
    	return lhs;
    }

  8. #8
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Overloading an operator... I'm really not getting it.

    Do not consider operator overloading anything other than a simple function. This helps!!!

    Consider them normal functions and just look at the way they are used for the fundamental types or the types for which these are already defined. The arithmetic operators work on two operands, for ex, +/-/* etc. Now since there are two things that they work on the function needs to know what those two things(operands) are?

    So, we pass them as arguments to the function. For member functions we show only one argument because of the implicit "this" argument. So, member overloads work on "this" and the second argument commonly known as "rhs". For non-member overloads, there is no "this" involved hence you give two arguments. The operators would work for your types as the same way they work with the pre-defined types (like say int or double).. now they will work for your classes as well. That's it! (there are also operators that work on just one operand ++, --)

    That's all there is in Operator overloading 101 - the basics... Now, go ahead with whatever you want to read up higher on them... your basics is done.. operator overloading is not something more than mere functions... Hope this helps. Regards.

  9. #9
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Overloading an operator... I'm really not getting it.

    Quote Originally Posted by NMTop40
    but here operator+ is defined wrong as I so often see it.
    Could you elaborate? I don't see anything wrong with how it's defined. Thanks!

  10. #10
    Join Date
    Aug 2002
    Location
    Cluj-Napoca,Romania
    Posts
    3,496

    Re: Overloading an operator... I'm really not getting it.

    Quote Originally Posted by treuss
    Could you elaborate? I don't see anything wrong with how it's defined. Thanks!
    You should think how the + operator is used: b+c. b+c does not modify neither b nor c so you the standard requires you to declare it like this:

    Code:
    Counter operator+(const Counter& lhs, const Counter& rhs)
    {
            Counter result;
    	
            // + implementation goes here
    
    	return result;
    }
    Using the Counter operator+(Counter lhs, const Counter& rhs) will work as well. The problem in this case is ( aside from not conforming to the C++ standard) that the copy constructor is invoked. For small objects this might not be significant but it can cause serious problems for bigger ones.

  11. #11
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Overloading an operator... I'm really not getting it.

    Quote Originally Posted by PadexArt
    You should think how the + operator is used: b+c. b+c does not modify neither b nor c so you the standard requires you to declare it like this.
    I still don't see, what's wrong with declaring it as a function member? The implementation above does not modify the function member. The only mistake I see now, is that it is not declared as
    Code:
    Counter operator+ (const Counter &) const;

  12. #12
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading an operator... I'm really not getting it.

    I don't see anything wrong with how it's defined.
    Perhaps not wrong, but merely with an unexpected limitation.
    We might want to do something like:
    Code:
    a = 1 + b;
    If operator+ is a member of the class type, then this will fail. On the other hand, if operator+ was global, then 1 would be implicitly converted to the class type required (presumably an implicit constructor that accepts an int, or an operator int() is provided).

  13. #13
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading an operator... I'm really not getting it.

    the standard requires you to declare it like this
    hmm... I've been looking for direction on whether to have both argument const T& or to allow the first argument to pass by value, but my search was not fruitful. Now that you have confirmed my suspicions, could you point me to the section in the standard that has this mandate?

    The problem in this case is ( aside from not conforming to the C++ standard) that the copy constructor is invoked. For small objects this might not be significant but it can cause serious problems for bigger ones.
    Ah, but here's the thing. The implementation of the operator might invoke the copy constructor, so in such a case there would be no advantage gained by passing both arguments by reference. For example:
    Code:
    T operator+(const T& lhs, const T& rhs) {
    	T temp(lhs);
    	temp += rhs;
    	return temp;
    }
    would be logically equivalent to:
    Code:
    T operator+(T lhs, const T& rhs) {
    	lhs += rhs;
    	return lhs;
    }
    except that the latter does not use a temporary.

  14. #14
    Join Date
    Aug 2002
    Location
    Cluj-Napoca,Romania
    Posts
    3,496

    Re: Overloading an operator... I'm really not getting it.

    Ah, but here's the thing. The implementation of the operator might invoke the copy constructor, so in such a case there would be no advantage gained by passing both arguments by reference.
    no, they aren't.

    The T operator+(T lhs, const T& rhs) implementation results in 2 calls for the copy constructor: 1 when the l argument is received and 1 when the result is returned.

    The T operator+(const T& lhs, const T& rhs) implementation results in just 1 call for the copy constructor: when the result is returned.

  15. #15
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading an operator... I'm really not getting it.

    The T operator+(const T& lhs, const T& rhs) implementation results in just 1 call for the copy constructor: when the result is returned.
    That's assuming that operator+ is a friend function and the raw implementation of the operator lies within that function. In my example, a temporary is instantiated by passing the first argument to operator+ to the copy constructor. Then temporary's operator+= is invoked with the second argument to operator+ as the argument. In this case, operator+= implemented as a member function containing the raw implemention.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured