inheriting from a class with constructors

G

Guest

What is the proper way of defining a class that inherits from a base class
that has no constructor with 0 arguments?

The following code generates compiler error CS1501, "No overload for method
'BaseClass' takes '0' arguments".

class BaseClass
{
public BaseClass(double x)
{
}
}

class TestClass : BaseClass
{
}

Inserting the constructor

public TestClass(double x)
{
}

into TestClass still generates the same error.
 
M

Marcos Stefanakopolus

I think you want:

class TestClass : BaseClass {
public TestClass(double x) : base(x)
{
// whatever
}
}

This is "constructor chaining".
 
M

Mohammad

It goes something like this:

If you define a class without a constructor, then the compiler will
generate an implicit constructor that takes no arguments.

So, if you write:
class A
{
};

The compiler will generate:
class A
{
public A()
{
// does nothing.
}
}


However, if you define a class with a constructor, then the compiler
will NOT generate a default constructor for you.

So if you type:
class B
{
public B( double d )
{
// more code goes here.
}
}

The compiler will generate exactly that.

Suppose now that you want to inherit from B:

class C : B
{
public C()
{
// yet more code goes here.
}
}

Then the constructor for class C MUST call a constructor for class B.
Since you have not explicitly specified what constructir to call for
class B, the compiler will attempt to call a parametless constructor.

So, the compiler will TRY to generate:

class C : B
{
public C()
{
B();
}
}

But since you have already defined a constructor for class B, one that
DOES take a parameter, the compiler will not generate a default
parameterless constructor for B, and as such, the compilation will
fail.

To remedy this, either explicitly define a paramaterless constructor
for B, as follows:

class B
{
public B( double d )
{
// more code goes here.
}

public B()
{
// whatever.
}
}

Or, modify class C to explicitly call the constructor in class class B,
as follows:

class C : B
{
public C() : base(0.0)
{
// yet more code goes here.
}
}
 
G

Guest

Thank you, Mohammad. The way you have shown of defining a constructor with a
": base()" clause is exactly the feature I need. Problem solved.

What had originally confused me was that the compiler complained about a
wrong number of arguments, not a failure to invoke the base constructor. You
have made clear why it would do that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top