Sam Gomari
Sam Gomari

Reputation: 765

How to access protected variables of a child

I read the following statement , I am not sure if it's true, if it is can you elaborate with an example.

The child has access to the same member variables of the base class that is of the same INSTANCE.

The question I have though, is how to access protected variables of a child

  class A
    {
     private:
       class B* myBclass; 
     protected:
       int bc; 
     }

    class ChildofA : public A
    {
      public:
         childofA() {};
    }

    class B
    {
      public :
       B() {};
       virtual void fun1(A* anA);
    }


    class childofB : public B
    {
      public :
        void fun1(A* anA) 
           {
              anA.bc=1; << Problem here 
            }

    }

The above code complains about the fact that that variable bc is protected. I'd like to have fun1() in ChildofB retrieve the variable bc of the instance of the child class ChildofA. How do you go about fixing this (without friend method and get/setter).

Upvotes: 3

Views: 486

Answers (1)

Tommy
Tommy

Reputation: 100632

That means that childOfA has access to bc despite it being declared by A. The child has access to all public and protected instance variables. Protected means is "private, but to me and to my descendants, rather than just to me".

Inheritance doesn't give anything in the B hierarchy the ability to see the private storage of things in the A hierarchy. Declare a friend if you really must, though it's probably poor style, or if bc is meant to be accessible to other classes then make it public.

Upvotes: 3

Related Questions