Johnny
Johnny

Reputation: 83

"return *this" assignment operator overloading

Fraction& Fraction::operator= (const Fraction &fraction)
{
    // do the copy
    m_numerator = fraction.m_numerator;
    m_denominator = fraction.m_denominator;

    return *this;
}

int main()
{
    Fraction fiveThirds(5, 3);
    Fraction f;
    f = fiveThirds; // calls overloaded assignment
    std::cout << f;

    return 0;
}

I have some problems with the concept of return this when overloading the assignment operator.

In the main function f = fiveThirds will call the assignment operator, and it will return *this, i.e. return a Fraction object!

The problem is f = fiveThirds will return the object, but there isn't any Fraction object to receive it!

In the assignment chain x=y=z, y=z will return an object (k) which will be assigned to x, however x=k will also return an object, so who receives this object?

I've done my best to describe my problem.

Upvotes: 0

Views: 144

Answers (1)

eerorika
eerorika

Reputation: 238401

The problem is f = fiveThirds will return the object, but there isn't any Fraction object to receive it!

More accurately, it returns a reference to an object.

so who receives this object?

The return value is discarded.

There is no problem.

Upvotes: 2

Related Questions