Calling virtual methods in constructor
suggest changeIn C# you can call a virtual method from a constructor. C++ allows that too, but the dispatch is different. For example:
abstract class Base
{
protected Base()
{
_obj = CreateAnother();
}
protected virtual AnotherBase CreateAnother()
{
return new AnotherBase();
}
private readonly AnotherBase _obj;
}
sealed class Derived : Base
{
public Derived() { }
protected override AnotherBase CreateAnother()
{
return new AnotherDerived();
}
}
var test = new Derived();
// test._obj is AnotherDerived
In C#, that call uses the most derived override, so the base constructor already sees Derived.CreateAnother. In C++, the same call would use Base.CreateAnother, because the derived object is not constructed yet.
Be careful: the derived constructor body has not run yet, so derived fields still have their default values. This is dangerous (StyleCop warns about it) and is usually a bad practice.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents