Calling virtual method in base class constructor

(This answer applies to C# and Java. I believe C++ works differently on this matter.)

Calling a virtual method in a constructor is indeed dangerous, but sometimes it can end up with the cleanest code.

I would try to avoid it where possible, but without bending the design hugely. (For instance, the “initialize later” option prohibits immutability.) If you do use a virtual method in the constructor, document it very strongly. So long as everyone involved is aware of what it’s doing, it shouldn’t cause too many problems. I would try to limit the visibility though, as you’ve done in your first example.

EDIT: One thing which is important here is that there’s a difference between C# and Java in order of initialization. If you have a class such as:

public class Child : Parent
{
    private int foo = 10;

    protected override void ShowFoo()
    {
        Console.WriteLine(foo);
    }
}

where the Parent constructor calls ShowFoo, in C# it will display 10. The equivalent program in Java would display 0.

Leave a Comment