Jump to content
  • Advertisement
Sign in to follow this  
domin

C++ operator overloading (return types)

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!