Search code examples
c++objectpointersmember-functionsfunction-qualifier

C++ const method on non const pointer member


I was wondering how protect a non const pointer member from an object throught a const method. For example:

class B{
    public:
        B(){
            this->val=0;
        }

        void setVal(){
            this->val = 2;
        }

    private:
        int val;
};

class A{
    public:
        A():b(new B){}
        void changeMemberFromConstMethod() const{
            this->b->setVal();
        }
    private:
        B * b; // how to protect data pointed in A::changeMemberFromConstMethod
}

Is it possible to "protect" A::b data pointed from his method? After many research on web, no satisfied reponse found yet.

Thanks for your help.


Solution

  • Something like this, perhaps:

    template <typename T>
    class deep_const_ptr {
      T* p_;
    public:
      deep_const_ptr(T* p) : p_(p);
    
      T* operator->() { return p_;}
      const T* operator->() const { return p_;}
    };
    
    class A {
      deep_const_ptr<B> b = new B;
    };
    

    deep_const_ptr behaves like a const T* const pointer in A's const methods, and like T* in non-const methods. Fleshing the class out further is left as an exercise for the reader.