I can’t wrap my head around why m() in class a can access x and y through the b class and b class object if x and y are private. I know that when b inherits from a, b receives private members from a even though they can’t be used by b. But what is strange to me is that b members can’t use x and y, and classes other than a can’t get at the variables through b class and b class object, yet m() can access x and y through the b class and b class object.
Can someone explain this to me using a general rule that I missed or maybe an explanation about how the compiler does this ‘giving’ of base members to derived classes?
class a
{
private int x;
private static int y;
static void m()
{
b bobj = new b();
int mm = bobj.x;
int rr = b.y;
}
void n()
{
b bobj = new b();
int mm = bobj.x;
int rr = b.y;
}
}
class b : a
{
private int u;
private static int v;
static void o()
{
}
void p()
{
}
}
Code within a class declaration can access any private members declared by that class – it’s as simple as that. So code within
acan’t access private variables declared inb, but it can access private variables declared inavia an instance ofawhich also happens to be an instance ofb.Note that this line:
is effectively converted to
yis only declared bya– if it were really declared byb, it wouldn’t be accessible.See section 3.5 of the C# 4 language specification for more details.