locked
Access a protected member in derived classes RRS feed

  • Question

  • User583311198 posted

    Hi,

    I have a scenario as following:

    class A

    {

    protected int a;

    }

    class B:A{}

    class C: B{}

    Now I can access a in the class B easily, but how can I access 'a' in class C?

    Friday, July 18, 2014 2:26 PM

Answers

  • User-760709272 posted

    Not just immediate derived class, any derived class

    http://msdn.microsoft.com/en-gb/library/bcd5672a.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 21, 2014 8:20 AM
  • User-484054684 posted

    Yes, as the first code example I have shared as well, we can access any parent class variable in a derived class - that is the beautification of inheritance. Some may call it as "multi-level inheritance". 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 21, 2014 12:40 PM

All replies

  • User-484054684 posted

    Simple - use base keyword.

      class A
      {
        protected int a;
      }
    
      class B : A
      {  
        // Your class variables may go here

    // Method AccessParentInfo() { int result = base.a; // you can access parent's members by using base keyword } } class C : B { // Your class variables may go here

    // Method. AccessParentParentinfo() { int result = base.a; // You can access parent's members by using base keyword } }

    Friday, July 18, 2014 2:58 PM
  • User583311198 posted

    I tried below example:

    class A
        {
            protected int x = 10;
    
            public A()
            {
                Console.WriteLine("From A:x=" + x);
            }
        }
        class B : A
        {
            public void AceessXFromB()
            {
                x = 20;
                Console.WriteLine("From B:x=" + x);
            }
        }
        class C : B
        {
            public void AceessXFromC()
            {
                x = 30;
                Console.WriteLine("From C:x=" + x);
            }
        }

    The protected member of A i.e., x is easily accessible from C without giving any error.

    But  what I know about protected modifier is, it can only be accessible to immediate derived classes. So now my question is how the above code is getting executed ?

    Monday, July 21, 2014 8:12 AM
  • User-760709272 posted

    Not just immediate derived class, any derived class

    http://msdn.microsoft.com/en-gb/library/bcd5672a.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 21, 2014 8:20 AM
  • User-484054684 posted

    Yes, as the first code example I have shared as well, we can access any parent class variable in a derived class - that is the beautification of inheritance. Some may call it as "multi-level inheritance". 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 21, 2014 12:40 PM