I have read that private variables in a base class are technically inherited by child classes, but are not accessible.
If this is correct, why do we say they are inherited when presumably they can only be accessed by reflection?
I have read that private variables in a base class are technically inherited by child classes, but are not accessible.
If this is correct, why do we say they are inherited when presumably they can only be accessed by reflection?
why do we say they are inherited...
Personally, I don't. I consider inheritance to include those things that you can access in a child class, not those things that are hidden.
I could see someone saying that to be clear that inheritance includes all elements up the chain, but it strikes me as overly pedantic and not especially useful.
Subclassing is about inheriting implementation; and fields are an implementation detail.
The fields are indeed present, and are available via reflection. But ultimately, it is the base-classes job to manage the state of those fields via any public/protected/etc members.
But ultimately - if a base-class declares a property (and field) for property Foo
, then when you set that property the data has to go somewhere. The sub-class has to include all the fields from the base-class for it to make sense. This is also critical for field-based serialization frameworks (such as BinaryFormatter
).
Private fields are inherited in the sense, that they take up space on the heap when allocated. However, the derived class cannot access them directly.