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

## 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 on other sites
To allow you to write (for example):

Fraction a;
Fraction b;
Fraction c;

a = b = c; // yes, this is valid code

HTH,

##### 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 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 on other sites
Ok, it is clear now for me - thanks you all.

1. 1
2. 2
3. 3
Rutin
19
4. 4
khawk
14
5. 5
frob
12

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633657
• Total Posts
3013199
×