Search code examples
c++member-pointers

Derived class cannot use member pointer to protected base class member


include <stdio.h>

class Base
{
protected:
    int foo;
    int get_foo() { return foo; }
};

class Derived : public Base
{
public:
    void bar()
    {
        int Base::* i = &Base::foo;
        this->*i = 7;
        printf("foo is %d\n", get_foo());
    }
};


int main()
{
    Derived d;
    d.bar();
}

I don't understand why my derived type can't make a pointer to the protected member of the base class. It has privilege to access the member. It can call the similarly scoped function. Why can't it make a member pointer? I'm using gcc 4.1.2 and I get this error:

test.cc: In member function ‘void Derived::bar()’:
test.cc:6: error: ‘int Base::foo’ is protected
test.cc:15: error: within this context

Solution

  • By trial and error I found a solution that makes some sense. Even if it is a base class inherited member that you are pointing to, the pointer should still be a member pointer of the Derived class. So, the following code works:

    include <stdio.h>
    
    class Base
    {
    protected:
        int foo;
        int get_foo() { return foo; }
    };
    
    class Derived : public Base
    {
    public:
        void bar()
        {
            int Derived::* i = &Derived::foo;
            this->*i = 7;
            printf("foo is %d\n", get_foo());
        }
    };
    
    int main()
    {
        Derived d;
        d.bar();
    }
    

    If Base's members are scoped as private then you get the expected lack of access error.