Samuel
Samuel

Reputation: 61

I cant understand this access modifier

I am the beginner of C++. And I have a programming test today. But I cant understand this examples.

class A
{
public:
    int w;
};

class B : public A
{
public:
    int x;
};

class C : private A
{
public: int y;
};

class D : protected B
{
public: int z;
};

int main()
{
    D d;
    d.w = 10; // compile error
}

I thought (D d; d.w = 10) is correct, but it has compile error.

D derived by B (protected), and B derived by A (public). So, I think D can access A class member, because

Class B : public A { public:int x} ==> Class B { public: int w; int x;}

and Class D : protected B { public: int z} ==> class D {public: int z; protected: int w, int x;}

Why I am wrong?? Thank you!

Upvotes: 4

Views: 66

Answers (1)

user4581301
user4581301

Reputation: 33952

D can see members of A and B, but because of protected inheritance, only D and classes derived from D know that D is a B and can access B and A members. main is not derived from D, so main is not aware of D's inheritance of B and thus cannot access the inherited A and B members.

Upvotes: 3

Related Questions