-1

Given two abstract classes, the parent having a constructor

public abstract class MyAbstractBaseClass
{
  public MyAbstractBaseClass(string arg){}
}


public abstract class MyAbstractSubClass:MyAbstractBaseClass
{
  // Properties and Methods
}

, can we instantiate a concrete subclass?

public class MyConcreteSubClass:MyAbstractSubClass
{
  public MyConcreteSubClass() // Call MyAbstractBaseClass("aStrign")
  {
  }

One could create an Init() function in the base class, but this would be rather a workaround than a solution.

Dani
  • 2,602
  • 2
  • 23
  • 27

3 Answers3

3

Constructors are not inherited.

base for MyConcreteSubClass is MyAbstractSubClass, and MyAbstractSubClass does not have a constructor that accepts a string.

If you want the constructor "inherited", you have to redeclare it:

public abstract class MyAbstractSubClass : MyAbstractBaseClass
{
  public MyAbstractSubClass (string arg) : base(arg) {}
  // Properties and Methods
}

Then you can call it with base("hello") from MyConcreteSubClass.

Community
  • 1
  • 1
GSerg
  • 76,472
  • 17
  • 159
  • 346
0

The constructor in the sub class also needs a body:

public class MyConcreteSubClass : MyAbstractBaseClass
{
    public MyConcreteSubClass() : base("hello")
    {
    }
}
Oliver Hanappi
  • 12,046
  • 7
  • 51
  • 68
0
public class MyConcreteSubClass : MyAbstractBaseClass
{
  public MyConcreteSubClass():base("hello") {}   
}

You have to inherit from your BaseClass to compile it :)

S.L.
  • 1,056
  • 7
  • 15