Reputation: 1929
Why is that protected members in the base class where not accessible in the derived class?
class ClassA
{
public:
int publicmemberA;
protected:
int protectedmemberA;
private:
int privatememberA;
ClassA();
};
class ClassB : public ClassA
{
};
int main ()
{
ClassB b;
b.protectedmemberA; // this says it is not accesible, violation?
//.....
}
Upvotes: 6
Views: 8247
Reputation: 227390
Because the protected members are only visible inside the scope of class B. So you have access to it here for example:
class ClassB : public ClassA
{
void foo() { std::cout << protectedMember;}
};
but an expression such as
someInstance.someMember;
requires someMember
to be public.
Some related SO questions here and here.
Upvotes: 3
Reputation: 10487
You can only access protectedmemberA
from within the scope of B
(or A
) - you're trying to access it from within main()
Upvotes: 0
Reputation: 258568
You can access protectedmemberA
inside b
. You're attempting to access it from the outside. It has nothing to do with inheritance.
This happens for the same reason as the following:
class B
{
protected:
int x;
};
//...
B b;
b.x = 0; //also illegal
Upvotes: 10