Calling virtual methods in constructor

suggest change

In 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents