JMRC
JMRC

Reputation: 1514

access protected inherited member with pointer to base class

Can someone explain why this code doesn't work.

class A
{
public:
    A(void){}
    virtual ~A(void){}
protected:
    A* parent;
};

class B : public A
{
public:
    B(void){parent = new B;}
    ~B(void){delete parent;}
protected:
    int a;
};

class C : public B
{
public:
    C(void){}
    virtual ~C(void){}
    void f(void){ ((B*)parent)->a; }
};

How is it possible that C isn't able to access members of B?

If I convert parent to a C* in stead of a B* it works fine. But I don't want users to take any unnecessary risks. Is there a cleaner way access a?

Thanks.

Upvotes: 0

Views: 2914

Answers (1)

shakurov
shakurov

Reputation: 2518

From an object of the C class, you can access protected members of B, but only if they're part of some object of class C (maybe yours, maybe not). In other words, to access a from C, you need a pointer (or a reference) to C. This is what the protected modifier means.

The reason for this is the following. The ((B*)parent) pointer may point to some other subclass of B, completely different from C, and that subclass may have the a member inaccessible.

Upvotes: 8

Related Questions