On creating an object of child class, the constructor of the child class is called which first initiates the call for the parent class’s constructor. Since the constructor of the parent class is called so there must be an object of parent class corresponding to that child class object. How to access that parent class object.
For example –
public class MyBase
{
private int num;
public MyBase()
{
Console.WriteLine("In MyBase()");
}
public MyBase(int i)
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived : MyBase
{
static int i = 32;
// This constructor will call MyBase.MyBase()
public MyDerived(int ii) : base()
{
}
// This constructor will call MyBase.MyBase(int i)
public MyDerived() : base(i)
{
}
public static void Main()
{
Console.WriteLine("Main pRoagram");
//This creates a parent object since parent constructor MyBase() is called
MyDerived md = new MyDerived();
// passes i=32 in base class
MyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)
}
}
How to access the parent class object formed by creating the child class object MyDerived md = new MyDerived();
and MyDerived md1 = new MyDerived(1);
I tried to put a debugger on the lines where the child class’s object is initiated but there was no object of parent class. I tried to use base
keyword in many settings but it didn’t work
Prateek Tewary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.