#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