C++ student here:
Today, while writing a class, I noticed that I am able to modify a non-mutable field with a const method, if the field is passed by reference:
class Foo {
public:
void func1(int & _n) const { _n = 42; }
void func2() { func1(n); }
private:
int n;
};
int main() {
Foo foo;
foo.func2();
return EXIT_SUCCESS;
}
I know that it's possible because a const method simply uses a this to const, but if I pass the field as a reference, I can have direct access to it without passing through the this (I'm still learning and also still not very good at English, I may have said something wrong);
So, my question is:
What's the true utility of a const method, if a non-mutable field can be modified with a simple "trick"?
Thanks!