This one could be easily become one of the Job Interview Questions we publish here at Dev102.com, but I decided to write a “regular” post about this issue because it is an important concept and not a just a puzzle or a brain teaser. Take a look at the following code, can you tell what will the output be?

public class BaseType
 {
     public BaseType()
     {
         Console.WriteLine("Call base ctor.");
         DoSomething();
     }

     public virtual void DoSomething()
     {
         Console.WriteLine("Base DoSomething");
     }
 }

 public class DerivedType : BaseType
 {
     public DerivedType()
     {
         Console.WriteLine("Call derived ctor.");
     }

     public override void DoSomething()
     {
         Console.WriteLine("Derived DoSomething");
     }
 }

 public class MainClass
 {
     public static void Main()
     {
         DerivedType derived = new DerivedType();
         Console.ReadLine();
     }
 }

The output of this program is:

Call base ctor.
Derived DoSomething
Call derived ctor.

Can you see the problem here? There is something very wrong and dangerous in this code…

Explanation: When constructing the derived class, the base class is constructed first. If you call a virtual method from the base class constructor, the overridden method is called. But notice that when that overridden method is called, the derived class is not initialized because its constructor code was not executed yet. So, we are calling a method of an un-initialized instance… This is the explanation from MSDN: “When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed“.

Be aware of this matter because it is not a trivial issue and apparently, there are no errors or warnings generated by the compiler. So, the rule to remember is to never call virtual methods from constructors. Now, go and check your code, is there a possibility that you violated this rule?

Tags :

8 Responses to “Call Virtual Functions From Constructors?”


  1. James Curran

    Said on July 8, 2008 :

    It’s interesting to note that in C++, the reverse happens (i.e. “Base DoSomething” is printed).

    The funny thing is ObjectiveC developers (i.e, The Cult of Jobs aka Apple-heads) insist the C# behavior is correct (and necessary) while the C++ behavior is a design flaw. This comes from their complete misunderstanding of C++. Objective C doesn’t have constructors; you initialize an object by calling a virtual function called Init(). So, they think they can easily port their code by putting the call to Init() in the base ctor.

  2. Greg Beech

    Said on July 8, 2008 :

    A better rule to remember is never to call virtual methods from constructors in unsealed classes.

    If the class is sealed then because the method table is constructed up front you can guarantee which method will be called, and so it’s no different to calling a non-virtual method.

  3. Troy Goode

    Said on July 8, 2008 :

    Great post, Shahar. I encountered this issue last night when I foolishly tried to this exact thing; luckily ReSharper was there to stop me.

    At the time I wasn’t sure why ReSharper put a blue squiggly line under my virtual method call, but I figured better safe than sorry and removed the virtual keyword. Cargo cult programming at its best. =)

    Thanks again for enlightening me!

  4. configurator

    Said on July 9, 2008 :

    Also, you could take a look at
    http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx
    and http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx.

    It discusses the different order in which initializers are run.
    In a nutshell, the post says that because initializers are guaranteed to have run before any virtual methods, they are run bottom-to-top (derived-to-base), opposite of the constructors.
    I believe this is important to understand for anyone who doesn’t want to know that it ‘just works’ but wants to know HOW it works, which in my view any good developer should.

  5. JV

    Said on July 9, 2008 :

    I don’t really see a problem here, this is the way how virtuals and constructors work… The combination of them is indeed dangerous if you are not aware of how it works.

  6. David

    Said on September 16, 2009 :

    Hi Shahar, what language this post refers to? it is impossible to tell when you reach it directly from a web search, as I did.

    anyway, in C++ the behavior is opposite as mentioned above, which seems to me much more reasonable – while in BaseType ctor, my scope in BaseType, so its function should be called. why should I care that there are some objects dangling beneath me?

    however such technique should be avoided, anyway.

2 Trackback(s)

  1. Jul 9, 2008: Reflective Perspective - Chris Alcock » The Morning Brew #132
  2. Jul 21, 2008: Weekly Web Nuggets #20 : Code Monkey Labs

Post a Comment