#819 – A Private Constructor May Prevent Inheritance

You can make a constructor private to restrict creation of an instance of the class only to code within the class.

If all constructors in a class are private, this means that a derived class is also prevented from calling a constructor.  Because the derived class must be able to call some constructor on the parent class, this will effectively prevent the creation of any derived class.

Assume that a Dog class defines a single constructor and makes it private.  In the code shown below, the Terrier class defines a constructor, which would implicitly call the default constructor in the base class.  Because that constructor is private, we get a compiler error and can’t create the Terrier class.

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

        public Terrier(string name, int age, double feistyFactor)
        {
            Name = name;
            Age = age;
            FeistyFactor = feistyFactor;
        }
    }

819-001

Advertisements