#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