Inheritance with base class constructor with parameters

zeusalmighty picture zeusalmighty · Jun 7, 2015 · Viewed 123.2k times · Source

Simple code:

class foo
{
    private int a;
    private int b;

    public foo(int x, int y)
    {
        a = x;
        b = y;
    }
}

class bar : foo
{
    private int c;
    public bar(int a, int b) => c = a * b;
}

Visual Studio complains about the bar constructor:

Error CS7036 There is no argument given that corresponds to the required formal parameter x of foo.foo(int, int).

What?

Answer

Dmitry picture Dmitry · Jun 7, 2015

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}