Deriving from a class with 3 constructors.

C

craigkenisston

Hi,

I have a class with 3 constructors, one takes no arguments, other take
an string and other an xml document.

I want to derive another class of it, I don't need a different
constructor so I didn't override nor rewrite any of its constructors.
When I try to compile I get the error :

No overloaded method for "MyDerivedClassConstructor" takes 1 argument.

The error is on a line to create the derived class passing 1 argument.

Why this ? It seems like the derived class "dont see" the parent's
constructors ?
 
Y

Yunus Emre ALPÖZEN [MCSD.NET]

What about the modifier of your constructors? Here is a sample and it
compiles without any error...


class SampleClass
{
public SampleClass() { }
public SampleClass(string s) { }
public SampleClass(XmlDocument doc) { }
}
class AnotherSampleClass : SampleClass
{
}
 
B

Bruce Wood

No overloaded method for "MyDerivedClassConstructor" takes 1 argument.
The error is on a line to create the derived class passing 1 argument.
Why this ? It seems like the derived class "dont see" the parent's constructors ?

The derived class certainly can "see" the parent's constructors. What
it doesn't do is _inherit_ its parent's constructors. A class has
however many constructors it declares, regardless of how many
constructors its parent class has. If you want your derived class to
have all three constructors, then you must code it like this:

public class DerivedClass : ParentClass
{
public DerivedClass() : base() { }
public DerivedClass(string s) : base(s) { }
public DerivedClass(XmlDocument xml) : base(xml) { }
}

You can leave the constructor implementations blank (thus the empty
braces { } ), but you must declare the constructors and indicate which
base class constructor they should call.
 
C

craigkenisston

Thanks, that worked !

I found other articles about this not inheritence of constructors.
I think I heard of it before, but didn't remember well.
It seemed very natural to think that I'd be able to access the parent's
constructor just like that, since they were public.
 

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