Search code examples
c++pointersconstantsmember-variables

C++ : forbid a class to change the value pointed to by a pointer member variable


I apologize if the title sounds abstruse, let me make that simple with an example :

class A
{
public:
    A(int *flag) : flag_(flag) {}
    void foo();
private:
    void bar();
    int *flag_;
};

The question is: can I prevent this class from changing the value pointed to by flag_?

Note : I'm thinking, maybe I want to write something like const int * flag_, but I do not want to make the value pointed to by flag "irrevocably" constant. In my case, this value is the value of some member variable of some other class, which can be changed.

Thanks for your insights!


Solution

  • const int *flag_; will not modify the constness of the actual variable passed in, it just defines how flag_ can be used. Whatever you pass into A's constructor will not have its constness changed. const isn't a runtime change, it's merely syntax to prevent the coder from accidentally modifying a value. You can do yourself one better and make it const int *const flag_; which will prevent A from modifying *flag_ AND flag_ won't be reassignable.