+ 8
A question about const in C++
I saw this paragraph in C++ lesson: In addition, a compiler error is generated when any const member function attempts to change a member variable or to call a non-const member function. But in my program, I can change the members of another class called Game. Which point I am missing? https://code.sololearn.com/c2BJ0e8PpDky/?ref=app
2 Answers
+ 2
Hello Joseph,
Good question.
For what I understand, you can not change the member variables of a 'const' object.
But in your code you are changing the member variable (name) of a 'non-const' object. (instance of Game)
The 'Person' object is the one that is 'const', not the 'Game' object.
I made a code to show the error when I try to change the member variable of a const object:
https://code.sololearn.com/ci4HWB989A0j/?ref=app
+ 3
Maybe this helps you:
https://stackoverflow.com/questions/3062360/const-member-function-vs-const-friend-function
"the const tells the compiler that the function won't modify the class X object that the implicit this parameter points to. The class Y object that's passed as a reference isn't const."