0

I just want make sure I'm doing and thinking right about inheritance and constructors if I have more than one sub class. My classes looks like this, Shape is the base class and the other derived classes

Shape<-----Shape2D<------Box

Is this code correct? it's working, but I'm just wondering if this is the best way?

    public Shape(int inputA, int inputB)
    {
        valueA = inputA;
        valueB = inputB;
    }

    public Shape2D(int inputA, int inputB) : base(inputA, inputB)
    {

    }

    public Box(int inputA, int inputB) : base(inputA, inputB)
    {

    }
3D-kreativ
  • 9,053
  • 37
  • 102
  • 159
  • 1
    As you can see in [this answer](http://stackoverflow.com/questions/12051/calling-base-constructor-in-c-sharp), yes it's the __only__ way to call a base constructor – Steve Jun 08 '12 at 09:06

2 Answers2

1

There is nothing that jumps out from your code example - the chaining looks fine, and when constructing Box, valueA and valueB will get populated as expected.

Not sure what you mean by "best way" - constructor chaining in this manner is absolutely fine.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

Yes it seems correct to me.

If you don't want to do any special initialization in your descendant classes, you can delegate the initialization task to the base class in the hierarchy. The members variables defined there, so it can handle any needed initialization.

If you need something special in the descendants, then you have to handle the special initialization there. But until you need those initializations exactly the same, I think this is the suggested way to do it.

Do you thought something this in your question?

Csaba Benko
  • 1,101
  • 8
  • 15