#768 – When to Call the Constructor of a Base Class

You can use the base keyword in a constructor, to call the constructor of a class’ base class.  You’d most typically do this to allow the constructor in the base class to initialize the data members that are defined in the base class.  Then the constructor of the derived class can initialize its own data members.

In the example below, the Terrier constructor uses the base keyword to invoke the Dog constructor.  Note that the Dog constructor will be executed first.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Console.WriteLine("Dog constructor");
            Name = name;
            Age = age;
        }
    }

    public class Terrier : Dog
    {
        public double GrowlFactor { get; set; }

        public Terrier(string name, int age, double growlFactor)
            : base(name, age)
        {
            Console.WriteLine("Terrier constructor");
            GrowlFactor = growlFactor;
        }
    }

768-001

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.

2 Responses to #768 – When to Call the Constructor of a Base Class

  1. Pingback: When to Call the Constructor of a Base Class. | Sriramjithendra

  2. Pingback: Dew Drop – January 29, 2013 (#1,489) | Alvin Ashcraft's Morning Dew

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: