I’m not sure why this is happening – hoping someone can explain it!
I have a base class called BaseRequest with this in it:
protected int cartNumber;
I have a derived class, which inherits BaseRequest. It has a public field and constructor as follows:
public int currentCartNumber;
public ExtendedBaseRequest(int cartNumber)
{
currentCartNumber = cartNumber;
}
Yes, I know it’s a bit silly to have a parameter with the same name as the protected field in the base class, but I didn’t notice it until now!
This compiles and runs, but the public currentCartNumber value in the derived class is not set as it uses the value from the base class, which is always zero as initialised.
Shouldn’t the compiler moan about this because the declaration of cartNumber in the constructor’s signature has the same name as the one in the base?
Looking forward to hearing from you.
Your analysis of what’s happening is incorrect. There’s something else going on here.
Are you sure that you’re not passing
0into the constructor?The unqualified
cartNumberwill always refer to the parameter. The inherited field would need to be qualified withthisorbase.In the code shown in the question, the statement
currentCartNumber = cartNumberwill assign the value of thecartNumberparameter to thecurrentCartNumberfield.