#831 – Implementing a Copy Constructor in a Derived Class

A copy constructor is a constructor that you can define which initializes an instance of a class based on a different instance of the same class.

If a base class includes a copy constructor, you can add a copy constructor to a derived class, from which you call the copy constructor of the base class.

Here’s an example.

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

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

        public Dog(Dog otherDog)
        {
            Name = otherDog.Name;
            Age = otherDog.Age;
            Collar = new DogCollar(otherDog.Collar);
        }
    }

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

        public Terrier(string name, int age, double growlFactor)
            : base(name, age)
        {
            GrowlFactor = growlFactor;
        }

        public Terrier(Terrier otherTerrier)
            : base(otherTerrier)
        {
            GrowlFactor = otherTerrier.GrowlFactor;
        }
    }
Advertisement

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

2 Responses to #831 – Implementing a Copy Constructor in a Derived Class

  1. remberry says:

    Nice example, but wich contructor is called first when using “Terrier(string name, int age, double growlFactor)” ?

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 )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: