Bird
0
0

Examine the code below and identify the issue:

medium📝 Debug Q7 of 15
C Sharp (C#) - Inheritance

Examine the code below and identify the issue:

class Parent {
    protected int data = 100;
}

class Child : Parent {
    void ShowData() {
        Parent p = new Parent();
        System.Console.WriteLine(p.data);
    }
}
AThe 'data' field should be declared as public to be accessible.
BCannot access 'data' through an instance of Parent inside Child.
CChild class cannot inherit from Parent because 'data' is protected.
DNo error; the code will compile and run correctly.
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected access

    Protected members are accessible within the class and derived classes, but only through the derived class itself, not through instances of the base class.
  2. Step 2: Analyze the code

    In 'ShowData', accessing 'p.data' is invalid because 'p' is an instance of Parent, not Child.
  3. Final Answer:

    Cannot access 'data' through an instance of Parent inside Child. -> Option B
  4. Quick Check:

    Protected members accessed only via inheritance, not base instances [OK]
Quick Trick: Protected accessed via inheritance, not base instances [OK]
Common Mistakes:
MISTAKES
  • Assuming protected members can be accessed via base class instances
  • Thinking protected means public access
  • Believing inheritance is blocked by protected members

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes