Inheritance with base class constructor with parameters

134.9k views Asked by At

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?

2

There are 2 answers

3
Dmitry On BEST ANSWER

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;
}
0
guitar80 On

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

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

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.