#330 – Derived Classes Do Not Inherit Constructors

A derived class inherits all of the members of a base class except for its constructors.

You must define a constructor in a derived class unless the base class has defined a default (parameterless) constructor.  If you don’t define a constructor in the derived class, the default constructor in the base class is called implicitly.

When you define a constructor in a derived class, you can call a constructor in the base class by using the base keyword.

Here’s an example:

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

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

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

        // Call the Name/Age constructor in the base class
        public Terrier(string name, int age, string attitude)
            : base(name, age)
        {
            Attitude = attitude;
        }
    }
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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: