class Foo {
public:
int a = 1;
};
class Bar {
public:
Foo *foo_ptr = new Foo;
};
int main() {
const Bar bar;
bar.foo_ptr.a++; // valid: a == 2
bar.foo_ptr = nullptr; // invalid: foo_ptr is const
}
I understand, why code above is correct - object bar is constant, so foo_ptr is constant pointer to a non-const Foo object. But I think it's a bit illogical. Why Foo object also did not become const?
What should I do, if I want Bar object to become absolute const here, and the foo_ptr to be a constant pointer to a constant object?
For example, I send Bar object to some method, and I don't want it or any Foo objects in it to be modifiable.
mutablemight come in handy.bar.foo_ptr.a++;whenbaris notconstwhile disallowing it whenbarisconst.constnature, instead of just making the raw pointer member variablepublic. Anyways understanding the difference of aconstpointer vs a pointer to aconstobject lays out the basis knowledge, how to implement such.publicfunctions and not expose the pointer as apublicmember variable. Understandingconstpointer vs pointer toconstobject is necessary but that does not necessarily help with their objective, assuming we, including the OP, are on the same page on the objective.