#619 – Calling the Constructor in a Base Class

Because a derived class does not inherit any of the constructors of the base class, it must do all of the initialization that the base class normally does.  It normally does this by using the base keyword to call the constructor of the base class.

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

        public Dog(string name)
        {
            Console.WriteLine("In Dog constructor");
            Name = name;
        }
    }

    public class Terrier : Dog
    {
        public string Temperament { get; set; }

        public Terrier(string name, string temperament) : base(name)
        {
            Console.WriteLine("In Terrier constructor");
            Temperament = temperament;
        }
    }

In the example above, the sequence when creating a Terrier object is:

  • Client code passes in name and temperament
  • Terrier constructor invokes the Dog constructor using the base keyword and passing the name parameter
  • Dog constructor does its initialization
  • Terrier constructor does its initialization

 

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 #619 – Calling the Constructor in a Base Class

  1. Pingback: #768 – When to Call the Constructor of a Base Class « 2,000 Things You Should Know About C#

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

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: