#331 – Calling a Base Class Constructor Implicitly vs. Explicitly

In a derived class, you can call a constructor in the base class explicitly using the base keyword.

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

        public Terrier(string name, int age, string attitude)
            : base(name, age)
        {
            Attitude = attitude;
        }

If you don’t explicitly call a base class constructor, the default (parameterless) constructor is called implicitly.

        public Terrier(string name, int age, string attitude)
        {
            // Default Dog constructor has already been called
            //   at this point.
            Name = name;
            Age = age;
            Attitude = attitude;
        }

If you do omit the base keyword, the base class must define a default (parameterless) constructor.  If it doesn’t, the compiler will complain that the base class doesn’t have a constructor that takes 0 arguments.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Connecting to %s

%d bloggers like this: