Sign in to follow this  
domin

C++ operator overloading (return types)

Recommended Posts

Hi all. Just simple question - why in example below all "=" operators (+=, -=, *=, /=) returns a reference to Fraction? Is it necessary? And what is its purpose? Thanks for any info.
 
class Fraction {
public:
    Fraction(int num = 0, int den = 1)
    {
        this->num = num;
        this->den = den;
    }
    Fraction& operator+=(const Fraction &rhs)
    {
        this->num = rhs.den * this->num +
            this->den * rhs.num;
        this->den = this->den * rhs.den;
        return *this;
    }
    Fraction& operator-=(const Fraction &rhs)
    {
        this->num = rhs.den * this->num - 
            this->den * rhs.num;
        this->den = this->den * rhs.den;
        return *this;
    }
    Fraction& operator*=(const Fraction &rhs)
    {
        this->num = this->num * rhs.num;
        this->den = this->den * rhs.den;
        return *this;
    }
    Fraction& operator/=(const Fraction &rhs)
    {
        this->num = this->num * rhs.den;
        this->den = this->den * rhs.num;
    return *this;
    }
    void print() 
    {
        cout << num << "/" << den << endl;
    }
private:
    int num;
    int den;
}; 

Share this post


Link to post
Share on other sites
Simple, to allow statements like:

Fraction a, b, c;
a = b = c = Fraction(4, 3);

The assignment operators are executed in right-to-left order here, so a, b and c all get assigned the same value. It's not mandatory, but usefull now and then, and since the default types act like this, it's sort of expected behaviour.

EDIT: got beaten to it. :)

Share this post


Link to post
Share on other sites
The question of the OP was about the other assignment operators which include an operation i.e. +=, -=, *=, /= etc. The argument is similar though; it allows you to write the somewhat unnatural and confusing

Fraction a;
Fraction b;
Fraction c;

a = b += c;


(which increments b by c and asigns the result (the new b) to a; equivalent to b += c; a = b).

Illco

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this