6

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

3 Answers 3

10

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
0
3

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.

2
  • tnx juan, any good situation on which a protected modifier is preferred? still cant gets its significance :( Commented Apr 21, 2012 at 14:45
  • I cannot think of a good reason to use a protected member variable. I have seen the use of protected functions when you want to allow derived classes to use some base class functionality, without making that functionality public. I would say, only use it if you really know what you are doing! Commented Apr 21, 2012 at 14:51
0

You can only access protectedmemberA from within the scope of B (or A) - you're trying to access it from within main()

Not the answer you're looking for? Browse other questions tagged or ask your own question.