User Id :    Password :      New Member   Forgot Password  
 
Call Virtual Functions From Constructors?
Description it is an important concept and not a just a puzzle or a brain teaser.   No. of Views     1122
  Rating     3
Author Rajat Sharma   Posted On     25 Aug 2011
Tags C#    

Sample Code   Download Code

Take a look at the following code, can you tell what will the output be?

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

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

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

     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 Sector.
Derived DoSomething.
Call derived Sector.

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?

 

About Author

About Author N/A Rajat Sharma
No Photo
 
Country India
Company ISHIR
Home Page N/A

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

 
 
Posted By Annonymous on 02 Sep 2011 at 05:35 PM
 
The genius store called, they're runnnig out of you.
 
 
 
Posted By Najmul Hoda on 26 Aug 2011 at 01:36 PM
 
Nice article Rajat.
Thanks for sharing.
I have not tested the code but looks interesting. I will check.
Thanks
 
 
   
Write your comment here.
Comment
Verification Code