Note: this article is published on 07/23/2024.

These two articles are with similar topics, we make them together:

Question:

Can a Private Member be Inherited by Derived Class? --- This is very interesting question.

When I moved into computer science fileld from physical science, I remember I learnt for Inheritance:

However, if I search for this topic, even in some interview guide, most of them say that private member are not inherited.

What is the puzzle?

Conclusion:

We discuss C#, while C# is created by Microsoft. Say Microsoft (Tutorial: Introduction to Inheritance - C# | Microsoft Learn):

What is inheritance?

Not all members of a base class are inherited by derived classes. The following members are not inherited:

While all other members of a base class are inherited by derived classes, whether they are visible or not depends on their accessibility. A member's accessibility affects its visibility for derived classes as follows:

Demo:

This is a sample code from Microsoft [ref]:

public class A
{
    private int _value = 10;

    public class B : A
    {
        public int GetValue()
        {
            return _value;
        }
    }
}

public class C : A
{
    //    public int GetValue()
    //    {
    //        return _value;
    //    }
}

public class AccessExample
{
    public static void Main(string[] args)
    {
        var b = new A.B();
        Console.WriteLine(b.GetValue());
    }
}
// The example displays the following output:
//       10

A private field is defined at Line 3 in class A, class C is inherited from class A, if we take off the commend out linew from Line 16-19 above, there will be an error, like:

It is saying, the private filed A._value is inherited, but not accessable.

On the other hand, class B (Line 5) is defined inside class A, and also inherited from class A. class B can read the A._value (the value from parent class).

Comment out the error line in class C, run the program we got

That is saying, the private field A._value is inherited by class B and can be accessable by class B, the nested class inside A.

References: