Derived class cannot use member pointer for protected element of base class

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 do not understand why my derived type cannot make a pointer to a protected member of the base class. He has privilege to access the member. It can cause a similar function. Why can't it point to a member pointer? I am using gcc 4.1.2 and I get this error:

test.cc: In member functionvoid Derived::bar()’:
test.cc:6: error: ‘int Base::foois protected
test.cc:15: error: within this context
+4
source share
1 answer

As a result of trial and error, I found a solution that makes sense. Even if it is an inherited element of the base class that you are pointing to, the pointer must 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 the Base elements are restricted as private, you get the expected access error.

+5

All Articles