I was wondering how protect a non const pointer member from an object throught a const method. For example:
class B{
public:
B(){
thi
The problem you have is that a const
method makes all the member variables const
. In this case however, it makes the pointer const
. Specifically, it's as if all you have is B * const b
, which means a constant pointer to a (still) mutable B
. If you do not declare your member variable as const B * b
, (that is, a mutable pointer to a constant B
), then there is no way to protect from this behavior.
If all you need is a const B
, then by all means, define A
like this:
class A {
public:
A() : b(new B) {}
// This WILL give an error now.
void changeMemberFromConstMethod() const { b->setVal(); }
private:
const B* b;
}
However, if other methods of A
mutate B
, then all you can do is make sure that B
does not get mutated in your const
methods of A
.