0

I have a base class:

public class Base {
  public string Foo { get; set; }
  public float Bar { get; set; }
  public float Foobar { get; set; }

  public Base (string foo, float bar, float foobar) {
      Foo = foo;
      Bar = bar;
      Foobar = foobar;
  }
}

I get an error when I attempt to add a class that extends this:

public class Derived : Base {
    public Base derived = new Derived ("Foo", 0f, 0f);
}

The error recieved states the following: Base does not contain a constructor that takes 0 arguments

I get this error on line 1 of the Derived class. Any fixes/reasons why this is happening?

  • 3
    Constructors aren't inherited. Declare a constructor in `Derived` which takes the same arguments and calls the base constructor using the syntax `public Derived(...) : base(...)`. – Michael Liu Dec 09 '16 at 20:53

3 Answers3

8

Without defining a constructor in the derived class, the default is a parameterless constructor. Which the base class doesn't have, so the derived class has no way of instantiating its base class (and, thus, itself).

Define a constructor in the derived class which uses the base class' constructor:

public Derived(string foo, float bar, float foobar) : base(foo, bar, foobar) { }

This is just a pass-through constructor. You could also use a parameterless one if you want, but you'd still need to use the base class' constructor with some values. For example:

public Derived() : base("foo", 1.0, 2.0) { }

It's a normal constructor like any other, and can contain any logic you like, but it needs to invoke the base class' only constructor with some values.


Note: This means you probably don't need this at all:

public Base derived = new Derived ("Foo", 0f, 0f);

It looks like you're trying to create an instance of Base as a member of Derived. But Derived is an instance of Base. If you want to use Base as an instance like that then you wouldn't want to use inheritance:

public class Derived {  // not inheriting from Base
    public Base base = new Base ("Foo", 0f, 0f);
}

Of course, at that point "base" and "derived" would be misleading names, since these classes wouldn't actually be in an inheritance structure.

David
  • 208,112
  • 36
  • 198
  • 279
4

Since the constructor of class Base accepts three parameters, you need to pass the values for those parameters from the constructor of class Derived:

public Derived(string foo, float bar, float foobar): base(foo, bar, foobar) {}
Ivan Vargas
  • 703
  • 3
  • 9
0

try this:

public class Derived : Base
{
    public Derived() 
        : base("Foo", 0f, 0f)
    {

    }

    public Base derived = new Derived();
}

You may also use the object initializer syntax:

public Base derived = new Derived() { Foo = "Foo", Bar = 0f, Foobar = 0f };
Ian
  • 21
  • 4