Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of assignment operator overloading c++ [duplicate]

I'm new to C++ and I'm starting with learncpp website. In Assignment Operator Overloading chapter has those lines of code:

Fraction& Fraction::operator= (const Fraction &fraction)
{
    m_numerator = fraction.m_numerator;
    m_denominator = fraction.m_denominator;
    return *this;
}

The first thing is why overloading assignment have to return reference instead of value?

And second thing is since this is a pointer itself then *this will be represented as dereference so its value should be object, but return value of assignment operator is Fraction&. Do I have a misunderstanding here?

like image 644
sasorihuriko Avatar asked Dec 12 '25 13:12

sasorihuriko


1 Answers

A pointer is a data type that holds a memory address of the type the pointer points to, or nullptr if it doesn't refer to anything. (Or a dangling pointer, or a garbage value... but that's a bad place.)

So dereferencing a pointer by *this means that you are now dealing with the object pointed to by the pointer. Which is why this->foo and (*this).foo do the same thing.

Why does C++ have a this pointer, rather than (say) a self reference? That's just how C++ evolved, which Bjarne Stroustrup discusses at length in his excellent book The Design and Evolution of C++.

Back to your operator= situation. In C++, you can typically do this kind of construct: x = y = z;, which is ordered like x = (y = z); due to the right-to-left association of assignment.

If your assignment was void operator=(Fraction const&) then it could not be used to do assignment chaining. Not supporting assignment chaining would be "friction" for anyone used to the expected behavior of assignment and how C++ built-in types allow chaining.

Why return Fraction& versus Fraction object, is more than a simple performance optimization. Because if you did (x = y).negate(); the hypothetical negate method would be operating on a temporary rather than on x.

like image 99
Eljay Avatar answered Dec 14 '25 02:12

Eljay