#671 – A Base Class Constructor Can Call a Virtual Method

If a base class constructor calls a virtual method that is overridden in a derived class, the version of the method in the derived class is the one that will get called.

For example, assume that we have a Dog class that defines a virtual Bark method and a Terrier subclass that overrides the Bark method.

    public class Dog
    {
        public Dog()
        {
            Console.WriteLine("Dog constructor");
            Bark();
        }

        public virtual void Bark()
        {
            Console.WriteLine("Woof");
        }
    }

    public class Terrier : Dog
    {
        public Terrier()
            : base()
        {
            Console.WriteLine("Terrier constructor");
        }

        public override void Bark()
        {
            Console.WriteLine("Terrier barking!");
        }
    }

Assume you create an instance of a Terrier.

            Terrier t = new Terrier();

The Terrier constructor calls the Dog constructor, which invokes the Bark method.  But it’s the Bark method in Terrier that is called, rather than the Bark method in Dog.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #671 – A Base Class Constructor Can Call a Virtual Method

  1. Hao Jiang says:

    Calling virtual member function from constructor could be dangerous, though. See the post by Matt Howells in http://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: