Thread: += Operator

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    59

    += Operator

    I have a main file rational.cxx and a header file rational.h.
    Everything seems to be working except i can't get the +=, *=, -=, and /= operators to work in the rational.cxx file.
    I have a function in rational.h so I can use it which is below.

    Code:
    int operator += (const rational& lhs, const rational& rhs)
    {
        return lhs += rhs;
    }
    For example when I get to the point in the program where += is located in the rational.cxx file I get a Segmentation Fault. I can't find why it's doing this I'm hoping it's just a silly mistake I made. I forgot to say I'm using a class in the header file which is why I need to do this. So any help would be appreciated.
    Last edited by StarOrbs; 05-01-2005 at 03:37 PM.

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    You are getting a seg fault most likely because your function is never ending recursion.

    Also why is your += returning a bool instead of a rational reference?

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    I'm still new to this so I haven't really figured out what to use yet, I mean to type int though.

  4. #4
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Unless you have a specific reason to do otherwise your math operators return a reference or a new object of the type of thing you are doing the operatioin on.

    Also as a general rule your += -= *= /= and %= (if they are defined) are member functions.

    The problem I see from the little bit of code is that you defined the += operator in terms of itself. So the compiler doesn't know how to do += on rational so it calls your function which sees the += again and class the function again. This keeps going until you run out of memory and try to access some that doesn't belong to you

  5. #5
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    Silly me, thanks for that I realized one of my problems. I have to take the numerator of lhs and rhs and add the two. Now I just have to figure out how to do that. Any ideas? lol
    Last edited by StarOrbs; 05-01-2005 at 04:11 PM.

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Quote Originally Posted by StarOrbs
    Silly me, thanks for that I realized one of my problems. I have to take the numerator of lhs and rhs and add the two. Now I just have to figure out how to do that. Any ideas? lol
    [edit]
    Code:
    int operator += (const rational& lhs, const rational& rhs)
    {
        return lhs += rhs;
    }
    You don't list both objects as parameters. The lhs object is the one calling the operator+= method, so it should not be listed. You can access the lhs object's members directly by just using their names.

    [/edit]


    Presumably your objects lhs and rhs are defined something like this:
    Code:
    class myObject
    {
         int x;
         int y;
    
    [edit]don't need get/set methods-->methods of a class,
     like operator+=, can access private members directly[/edit]
    ....
    }
    So, you would do something like this inside operator+=:

    [edit]
    x += rhs.x;
    [/edit]


    and as Thantos pointed out, you want to return a reference to an object, which in this case I think should be the lhs object. That is so you can chain operations together like this:

    myObject1 += myObject2 += myObject3;

    Otherwise, I don't think you would need to return anything: your lhs object would already have the appropriate changes made inside the operator+= method. Also, you should be able to see that returning an int probably isn't correct. If you do this:

    myObject1 += myObject2;

    the return value is not assigned to a variable so it's discarded. If you wanted to assign the return value to a variable, you would need to do this:

    int result = (myObject1 += myObject2);

    Is that something you want to be doing? If not, the only time the return value would be important is in a chain:

    myObject1 += (myObject2 += myObject3);

    If the operator+= returns an int, then you are left with:

    myObject += someInt;

    and you probably don't even have an operator+= defined for an int type on the rhs. What you want to be left with is:

    myObject += Object2;
    Last edited by 7stud; 05-01-2005 at 10:15 PM.

  7. #7
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    I got the += working but for some reason when I got to *= I got snagged again. I'm trying to multiply, I'll just use your example.. x times a integer.. For example..
    x * 8 ..
    And in the .cxx file it would say x *= 8

    I hope I said that right.

  8. #8
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Think about what x * 8 means.

    Its simply:
    x + x + x + x + x + x + x + x

    Don't you already have an operator that defines addition?

  9. #9
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    I tried to figure out what you mean but it won't let me multiply something that is part of an object by an integer.

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Maybe this example will help you out:
    Code:
    #include <iostream>
    using namespace std;
    
    class Apple
    {
    	int size;
    
    public:
    
    	Apple(int s)
    	{
    		size = s;
    	}
    	Apple()
    	{
    		size = 0;
    	}
    
    	int getsize(){return size;}
    
    	Apple& operator+=(const Apple& rhs)
    	{
    		size += rhs.size;
    		return *this;  
                    //'this' is a pointer to the object that is calling this function, i.e.
                    //the object on the lhs, and dereferencing it gives you the object
    	}
    
    	Apple& operator*=(const Apple& rhs)
    	{
    		size *= rhs.size;
    		return *this;
    	}
    
    };
    
    int main()
    {
    	Apple A(5);
    	Apple B(2);
    
    	A += B;
    	cout<<A.getsize()<<endl;
    
    	A *= B;
    	cout<<A.getsize()<<endl;
    
    	return 0;
    }
    Last edited by 7stud; 05-01-2005 at 09:07 PM.

  11. #11
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    I understand what your typed but all that program does it ouput 0 to the screen. This is driving me nuts.

  12. #12
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    Let me post the code, maybe you guys will see where I'm going wrong. Don't worry about the rest of the code, I just need help with the operators.. += and such

    Code:
    #include <sstream>
    `
    class rational
    {
      private:
    	int num;
    	int den;
      
      public:
    	rational(int rn, int rd);
    	rational();
    	string tostring() const;
    	
    	int operator += (rational& rhs);
    	int operator -= (rational& rhs);
    	int operator *= (int& rhs);
    	int operator /= (rational& rhs);
    	
      	int compare (const rational& rhs) const;
      	int setden(int denom);
      	int setnum(int numer);
    	int denominator() const;
    	int numerator() const;
    
    	
    };
    ostream& operator << (ostream& os, const rational& r);
    
    
    
    rational::rational(int rn , int rd)
      : num(rn), den(rd)
    {}
      
    rational::rational()
      : num(0), den(1)
    {}
    
    
    int rational::compare (const rational& rhs) const
    {
    	if(den == rhs.den)
        	return 0;
        if(den > rhs.den)
        	return 1;
        if(den < rhs.den)
        	return -1;
    }
    
    int rational::setden(int denom)
    {
    	den = denom;
    }
    
    int rational::setnum(int numer)
    {
    	num = numer;
    }
    
    int rational::denominator() const
    {
        return den;
    }
    
    int rational::numerator() const
    {
        return num;
    }
    
    int rational::operator += (rational& rhs)
    {
    	num += rhs.num;
    	den += rhs.den;
    }
    
    int rational::operator -= (rational& rhs)
    {
        num -= rhs.num;
    	den -= rhs.den;
    }
    
    int rational::operator *= (int& rhs)
    {
        num *= rhs;
    	den *= rhs;
    }
    
    int rational::operator /= (rational& rhs)
    {
        num /= rhs.num;
    	den /= rhs.den;
    }
    
    string rational::tostring() const
    {
        ostringstream out;
        out << num << "/" << den;
        return out.str();
    }
    
    
    ostream& operator << (ostream& os, const rational& r)
    {
        os << r.tostring();
        return os;
    }

  13. #13
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Well your += doesn't really do what it should.

    1/2 + 3/1 != 4/3

    What is:
    1/2 * 5? Isn't it 5/2?

    So you can multiple 1 * 5 and leave the denomitor alone.

    Or you can add 1/2 + 1/2 + 1/2 + 1/2 + 1/2

  14. #14
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    For rational numbers, multiplication is usually easier than addition, so it doesn't really make sense to implement the latter in terms of the former.

    For multiplication you just multiply the two numerators and the two denominators.
    For addition, you have to multiply the two denominators with each other, the first numerator with the second denominator and vice versa, and then add the numerators.

    In both cases you finish by reducing the fraction.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  15. #15
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I understand what your typed but all that program does it ouput 0 to the screen.
    Well, I think that means one of two things:

    1) Your compiler is junk.
    2) Your copy and paste technique needs work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Failure to overload operator delete
    By Elysia in forum C++ Programming
    Replies: 16
    Last Post: 07-10-2008, 01:23 PM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Operator Overloading (Bug, or error in code?)
    By QuietWhistler in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2006, 08:38 AM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM