+ 3

"This" again

https://code.sololearn.com/c6IG9DlmvCFM/?ref=app How do the compilers know what the "This" pointer points to and why is there an "My class &obj"?

31st Mar 2018, 10:39 AM
何岱庭
何岱庭 - avatar
3 Respuestas
+ 2
Let's take the expression obj1 + obj2 in this code. When overloading the + operator the object left to the + is the "host" of the operation and the object to the right of the + is passed into the operator overloading method as a reference. In the function body the "this" tells the compiler that you want to access the variable of the host and the other one is accessible by using the reference passed into the function (obj.var). The method stores these in the variable 'var' of a newly created object, which then will get returned.
31st Mar 2018, 11:18 AM
Alex
Alex - avatar
+ 2
Maybe this explains it a bit better. I changed to code so that it modifies the var variables of both objects. https://code.sololearn.com/cPt8q2OBPk8R/?ref=app (never do such unintuitive operations in a real code. It's just for demonstration purposes :D)
31st Mar 2018, 11:24 AM
Alex
Alex - avatar
+ 1
Thank you,Alex! ☺
1st Apr 2018, 12:53 AM
何岱庭
何岱庭 - avatar