Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 358
Alex Avatar asked Aug 29 '14 20:08

Alex


2 Answers

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.

like image 55
Igor Tandetnik Avatar answered Oct 21 '22 04:10

Igor Tandetnik


If you change the member of A from

    B* b;

to

    B b;

then you will get the expected behavior.

class A{
    public:
        A() : b() {}

        void changeMemberFromConstMethod() const{
            this->b.setVal(); // This will produce a compiler error. 
        }
    private:
        B b;
}
like image 44
R Sahu Avatar answered Oct 21 '22 05:10

R Sahu