The "This" Thing In C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

The "This" Thing In C++

https://code.sololearn.com/cf7o6N8LKzA0/?ref=app What is the scope of the “This“ thing in this code?Why is it outputting 10?

16th Mar 2018, 2:49 AM
何岱庭
何岱庭 - avatar
5 Answers
+ 3
'This' means object itself. In your case, it is obj object. 1st: you print 'x' which is local x (value of 20) 2nd: you print 'this->x' (object attribute 'x') which should be present in obj object scope. However, it is not. So, it find in its parent class which is myClass. And there's 'x' in myClass scope. Then output is 10.
16th Mar 2018, 3:05 AM
Sylar
+ 2
Exactly! that is!
16th Mar 2018, 3:17 AM
Sylar
+ 2
Glad you got it! :)
16th Mar 2018, 3:21 AM
Sylar
+ 1
ohh hold on.Is it correct if I say the ”This->” thing in this code is the same as”obj.”?
16th Mar 2018, 3:16 AM
何岱庭
何岱庭 - avatar
+ 1
Oh I got it now.Thank you so much!
16th Mar 2018, 3:19 AM
何岱庭
何岱庭 - avatar