Search code examples
c++inheritanceprotectedprivate-members

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?
    //.....
}

Solution

  • 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