Search code examples
c#inheritanceconstructorparent

Creating Children Objects with Parents Variables


ok i've found alot of information close to an answer but nothing that really works and i really hope you guys can help.

imagine something like this

public class Parent
{
    public int A;
    int B;
    private int C;
    public Parent(int someIntA, int someIntB, int someIntC)
    {
        A = someIntA;
        B = someIntB;
        C = someIntC;
    }
}
public class Child : Parent
{
    public int D;
    // constructor
}

how can i create a constructor in such a way that when i create a object "Child" it has its own independent int A,B,C and D, Or do child objects not obtain its parents variable spots?


Solution

  • A child object always contains all of the attributes of its parent. But your child won't be able to access the parent's C as it is private to the parent.
    The new keyword is there to hide members. You should be able to use something like

    private new C;
    

    in your child class to hide the parent's member.

    See here for the description.