I have an Abstract Class having 2 overloaded constructors. I want to require all derived classes to implement both constructors as both variations support some of the virtual methods provided by Class A that would be very beneficial of all the derived classes. My model resembles the following:
public abstract class A
{
protected int _x {get;set;}
protected int _y {get;set;}
protected string _z {get;set;}
public A(int x, int y)
{
_x = x;
_y = y;
}
public A(int x, int y, string z)
{
_x = x;
_y = y;
_z = z;
}
}
I know I can declare the 1st constructor like this:
public class B : A { B(int x, int y) : base (x , y) {}
}
But how would one go about declaring the 2nd constructor of the Abstract class in the derived class?
You don't inherit constructors at all. You declare whichever constructors you want, and make sure that each one chains appropriately, either to a base class constructor, or to another constructor in the same class.
So for example, you could have:
public class B : A
{
public B(int x, int y) : base(x , y) {}
public B(int x, int y, string z) : base(x, y, z) {}
public B() : base(0, 0, "Hello!") {}
public B(int x) : this(x, 10, "Chained to B") {}
}
See more on this question at Stackoverflow