0

Why can't I change regVar?

class MyClass { public: MyClass(int a, int b); private: int regVar; const int constVar; }; MyClass::MyClass(int a, int b) : regVar(a), constVar(b) { regVar = 5; cout << regVar << endl; cout << constVar << endl; } int main() { MyClass obj(42, 33); }

5th Mar 2020, 11:54 AM
Si Thu Tun
4 Answers
+ 2
The last assignment to regVar is 5 so it will result in the output with value 5. What is that you didn't understand?
5th Mar 2020, 12:25 PM
Avinesh
Avinesh - avatar
+ 1
I tested your code in Code Playground and it runs just fine and outputs as expected.
6th Mar 2020, 4:50 PM
Ipang
+ 1
lol.. thanks a lot you both. It didn't work when I tried.
7th Mar 2020, 2:30 AM
Si Thu Tun
0
The program don't run. Why can't I change regVar value to 5 in that way? As it's not declared constant, it should be changed isn't it?
6th Mar 2020, 4:02 PM
Si Thu Tun