constructor inheritance

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Peter

    constructor inheritance

    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
  • Marc Gravell

    #2
    Re: constructor inheritance

    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

    Comment

    Working...