constructor inheritance

P

Peter

Hi

is it the case that if a class has som constructors, but not including
a no-parameter constructor, then if I inherit from this class I have to
also implement constructors which take the same parameters?


For example:

public class A
{
public A(int x)
{
}

public A(int x, int y)
{
}
}

public class B : A
{
}

then in B, I have to define the same constructors as in A? And I cannot
for example define a constructor which takes a string?

Thanksm
Peter
 
M

Marc Gravell

Constructors are not inherited. You can whatever you like in B; by
default it would have a parameterless constructor that calls base()
[which doesn't exist], but you can do whatever you want.

In this case, since there is no parameterless base constructor, the
only condition is that you must indicate which base constructor you
want to call, and with what values; for example

// uses int.Parse
public B(string s, int i) : base(int.Parse(s), i) {

}
// always calls with a constant (for some reason)
public B(string s) : base(4,5) {
// do something with s
}

Marc
 

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