+ 2

Why is this printing '4232078'?

#include <iostream> using namespace std; class MyClass { private: int myVar; public: MyClass(int a){ a = myVar; } int getMyVar(){ return myVar; } }; int main() { MyClass myObj(7); cout<<myObj.getMyVar()<<endl; }

10th Aug 2017, 2:30 AM
Nick Chesterton
Nick Chesterton - avatar
7 odpowiedzi
10th Aug 2017, 3:13 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Because you don't give myVar value, so it's value is random. Your bug is at line 9. You should write "myVar=a" if you want the answer is 7. Hope I have answered your question.
10th Aug 2017, 3:07 AM
懵懂蔡
懵懂蔡 - avatar
+ 3
I'll try this out in CodePlayground (FYI, if you add a link to your codes there for visitors/comments that's super useful)
10th Aug 2017, 3:01 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
Expanding on Hatsy's answer (because it's nice to see how things are allocated): When c++ initializes your object, it creates a data structure in memory with the size of its internal variables. Your class (static or instantiated) is 4 bytes long, so each instance (with its uninitialized int myVar) gets 4-bytes of what was there before. It is interesting that "what was there before" is a constant across submissions (and across all runtime servers; I ran this a lot). Determinism implies that it's left over from the wrapper, compiler or bootstrapping process itself (which may or may not be a security concern). The actual constant value is different below because my debugging shifted the allocation address, but it's the same question / in the same vicinity (and notice how my two copies of the object are allocated 4 bytes apart): https://code.sololearn.com/crkEJL64XKLG/?ref=app
10th Aug 2017, 9:07 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Turns out "a = myVar" was the issue. Needed to be flipped: "myVar = a". Didn't realize the order mattered, but it makes sense: myVar is receiving a new assignment/value, so it needs to be on the left. Still no idea what the mysterious number is...
10th Aug 2017, 3:02 AM
Nick Chesterton
Nick Chesterton - avatar
+ 2
Thanks, Kirk. Didn't know I could do that. I'll do as you say in future!
10th Aug 2017, 3:03 AM
Nick Chesterton
Nick Chesterton - avatar
+ 1
Okay, so I added "return 0;" to the main function, but it's still printing this weird number. Where's it getting that from? It's especially strange because a nearly identical practise code I used seems to work just fine at printing '32', as specified in its code: #include <iostream> using namespace std; class MyClass { public: MyClass(int a) { var = a; } int getVar() { return var; } private: int var; }; int main() { MyClass myObj(32); cout<<myObj.getVar()<<endl; return 0; }
10th Aug 2017, 2:41 AM
Nick Chesterton
Nick Chesterton - avatar