I'm probably doing this totally wrong..
public class BaseClass
{
public string result { get; set; }
public BaseClass(){}
public BaseClass(string x) {
result = doThing(x);
}
public virtual string doThing(string x)
{
return x;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(){}
public DerivedClass(string x):base(x){}
public override string doThing(string x)
{
return "override" + x;
}
}
I'd like for a new DerivedClass("test") to have a result of "overridetest" but it doesn't: it calls the base method of doThing. Am I missing something? Do I need to make an AbstractClass and have both BaseClass and DerivedClass inherit from that, Derived class also overriding methods?
The problem is that you are making a virtual call in the constructor. The mechanics of this issue and possible workarounds are detailed here.
In short, the overridden function has not yet been constructed when you enter the constructor of the base class, therefore the virtual function in the base class is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With