Why does returning value work instead of class type? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does returning value work instead of class type?

Check the code I added the questions there. I am just confused. I should have returned *this. But I forgot about it. I did what I thought was right way and it worked. But is it actually the right way? Returning *this is also invoking copy constructors which wasn't the case before. https://code.sololearn.com/c29grpSJ6LAV/?ref=app

20th Jan 2020, 9:59 AM
Akib
Akib - avatar
3 Answers
+ 2
It works because the compiler knows how to convert the integer value that is actually returned to an INT value through the constructor you provided. It can use the constructor to perform an implicit conversion every time INT is required, but int is given. Note that the other way round won't work without the definition of a conversion operator. Now to some subtle errors in your code. The following lines would all give unexpected results when compiled in your main (test it if you want): cout << ( ( x = y ) = 5 ) << endl; // should print 5 cout << 1 + x << endl; // should print 6 cout << x-- << endl; // should print 5 First of all, the copy constructor is called because you return INT where it really should be INT&. The first is a pass-by-value operation, so a copy is created. This can be a problem with chained assignment, as can be seen in the first line above, because the original object is unaffected, the copy is. Returning a reference to the original object is the way to go. ...
20th Jan 2020, 10:44 AM
Shadow
Shadow - avatar
+ 2
Unary operators like + are usually not defined as member functions because now you cannot write int + INT since you can't overload the operator for int directly. Moving it out of the class allows you to specify both arguments, enabling you to overload for this case aswell. Otherwise, the second line would not compile (well, it would if the compiler knew how to convert INT to int, then it could use the INT + INT definition, but that would be less efficient). And third, both your pre- and post in-/ decrement operators do exactly the same thing, while typically they differ in what value is returned. To fix this, the post versions do not return the original object, but a copy of itself containing the old value before the operation happened. This way, the internal value can be in-/ decremented, but the old value can be returned. Putting all of this together, here is how it could look like: https://code.sololearn.com/cQ1GBh3X2qx0/?ref=app
20th Jan 2020, 10:52 AM
Shadow
Shadow - avatar
0
Thank you for explaining. I need to read it few more times to understand. The examples in the book are very straightforward 😅. Just need to research a bit more.
22nd Jan 2020, 4:23 AM
Akib
Akib - avatar