Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protected members are not accessible in derived classes

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?
    //.....
}
like image 402
WantIt Avatar asked Apr 21 '12 14:04

WantIt


2 Answers

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
like image 89
Luchian Grigore Avatar answered Sep 21 '22 00:09

Luchian Grigore


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.

like image 31
juanchopanza Avatar answered Sep 19 '22 00:09

juanchopanza