How can a C++ or Java compiler make sure that none of the member variables state is changed in a const
member function (mutable is exceptional).
Will the compiler do something like putting the code in a non-writable code segment or something like that?
The compiler doesn't make sure. It can't, since there's no rule
in the language that says that member variable state cannot
change in a const
member function. The only rule is that you
cannot change the state through the this
pointer (without
casting away const
).
For C++ const
checking is done at compile time through the logic of the compiler. It will ensure that if a function is marked const
then no changes will be made to the member variables. I don't think it has anything to do with the storage of the executable code.
For Java, I wasn't aware that there was the same const
paradigm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With