Reputation: 4963
I have read all over the internet and books that protected
member can be accessed within the class only and in the derived class only. I am experimenting with following code
class Program
{
static void Main(string[] args)
{
}
}
abstract class A
{
protected int n_IntA = 0;
public abstract void AMethod();
}
abstract class B : A
{
int nb;
public B()
{
}
public abstract void GetProtected();
public override void AMethod()
{
}
}
class C : B
{
public override void GetProtected()
{
// Here n_IntA is accessible why ??
}
}
But here in class c n_IntA
is accesible. Why? Derive class for A
is B
.So accessibility of n_IntA
must be upto the class B only ??
Upvotes: 1
Views: 62
Reputation: 2078
Protected members are always accessible from the derived class no matter what is the level of hierarchy. here in question n_IntA
is accessible because
C inherits from B that inherits from A
also you did not modified the specifier in class B it remains protected in B and same thing happens for C
Upvotes: 2
Reputation: 13207
The accessibility goes through ALL of the inheritance-tree.
If you are no explicitly hiding a member, for example using new
-operator, you can access These members far down the inheritance tree.
Take a look at MSDN and see how deep inheritance goes especially in the WinForms and WPF-classes. If you couldn't access members defined in System.Object
the entire framework would break...
From MSDN:
Use the access modifiers, public, protected, internal, or private, to specify one of the following declared accessibility levels for members.
...
protected | Access is limited to the containing class or types derived from the containing class.
Upvotes: 2