Abstract Base Constructor Question

  • Thread starter Thread starter Randy
  • Start date Start date
R

Randy

Problem reduced to simplist form:

abstract class myBase
{
myBase(int x)
{
Console.Writeline("x = {0}", x);
}
}
class mySubClass : myBase
{
mySubClass() {}
}

Yields the following error: "No overload for method 'myBase' takes '0'
arguments"

Any ideas on what I have to do to mySubClass to get this to compile?

Thanks,
Randy
 
In myBase, the only constructor you have takes a single argument. In
mySubClass, the only constructor takes no arguments. For inheritance to
work, the sub classed constructor must somehow call the base class
constructor. if there's no argument to pass, it doesn't know how.

If you change mySubClass to:

class mySubClass : myBase
{
mySubClass(int x) {}
}

that will work.

Optionally, you can specify which base class constructor to call and do
something like:

class mySubClass : myBase
{
mySubClass() : base(4) {}
}

In this case, we're passing the constant integer 4 to the base class
constructor.


Pete
 
Randy said:
Problem reduced to simplist form:

abstract class myBase
{
myBase(int x)
{
Console.Writeline("x = {0}", x);
}
}
class mySubClass : myBase
{
mySubClass() {}
}

Yields the following error: "No overload for method 'myBase' takes '0'
arguments"
basically
class mySubClass : myBase
{
mySubClass() : base(10) {}
}

in other words, you have to specifiy a value for the base constructor.
 
You're derived class needs to call the base classes constructor which
requires one parameter of type int. You need to modify the constructor of
the derived class to look like

mySubClass() : base(<some hard coded integer value here>) {}
or
mySubClass(int x) : base(x) {}
 
Yes. You need to pass the constructor parameters up to the parent class
constructor, like so:

abstract class myBase
{
myBase(int x)
{
Console.Writeline("x = {0}", x);
}
}
class mySubClass : myBase
{
mySubClass(int x): base(x) {}
}

Hope this helps!
 
Randy,

In addition to what the others said, you also have to make the base
constructor accessible to the derived class. It's currently private,
so it can't be used by mySubClass. Make it at least protected.



Mattias
 
Back
Top