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?
    //.....
}
vvavepacket
  • 1,882
  • 4
  • 25
  • 38

3 Answers3

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
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
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.

Community
  • 1
  • 1
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • tnx juan, any good situation on which a protected modifier is preferred? still cant gets its significance :( – vvavepacket Apr 21 '12 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! – juanchopanza Apr 21 '12 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()

Component 10
  • 10,247
  • 7
  • 47
  • 64