Search code examples
c#constructorabstract-class

Parameterized abstract class constructor


I have a class like below

public abstract class ABC
{
    int _a;
    public ABC(int a)
    {
        _a = a;
    }
    public abstract void computeA();
};

Is it mandatory for the derived class to supply the parameters for the base/abstract class constructor? Is there any way to initialize the derived class without supplying the parameters?

Thanks in advance.


Solution

  • Yes, you have to supply an argument to the base class constructor.

    Of course, the derived class may have a parameterless constructor - it can call the base class constructor any way it wants. For example:

    public class Foo : ABC
    {
        // Always pass 123 to the base class constructor
        public Foo() : base(123)
        {
        }
    }
    

    So you don't necessarily need to pass any information to the derived class constructor, but the derived class constructor must pass information to the base class constructor, if that only exposes a parameterized constructor.

    (Note that in real code Foo would also have to override computeA(), but that's irrelevant to the constructor part of the question, so I left it out of the sample.)