I'm not sure to understand why I can modify an object from a const method, look:
#include <iostream>
struct Foo {
int a = 0;
void change() {
a = 3;
}
};
struct Test {
Foo* f;
Test(): f{new Foo} {}
void test() const {
f->change();
}
};
int main()
{
Test t;
std::cout << "before: " << t.f->a << "\n";
t.test();
std::cout << "after: " << t.f->a << "\n";
}
Not only it compiles but it prints:
0
3
So I was able to modify the logical state of an object from a const method. Is that because I used a pointer?
The const
applies to the pointer itself, f
, not to what this pointer is pointing to. The type of f
inside your const
-qualified member function, Test::test()
, is Foo* const
(i.e., const
pointer to Foo
), not const Foo*
(i.e., pointer to const Foo
). That's why you can modify what the pointer is pointing to in spite of the const
qualification of the member function.
Note that the following sample member function, Test::test2()
, does fail to compile since it is const
-qualified and tries to modify the pointer data member, f
:
void Test::test2() const {
f = nullptr; // <-- error
}