I have a set of classes where my base has a constructor that takes a configuration object and handles transferring the values to its properties.
abstract class A { public A(ObjType MyObj){} }
abstract class B : A {}
class C : A {}
class D : B {}
class E : B {}
Is it possible to implicitly call a non-default base constructor from child classes or would I need to explicitly implement the signature up the chain to do it via constructors?
abstract class A { public A(ObjType MyObj){} }
abstract class B : A { public A(ObjType MyObj) : base(MyObj){} }
class C : A { public A(ObjType MyObj) : base(MyObj){} }
class D : B { public A(ObjType MyObj) : base(MyObj){} }
class E : B { public A(ObjType MyObj) : base(MyObj){} }
If that is the case, is it better to just implement a method in the base then have my factory immediately call the method after creating the object?
No it's not possible to call a non-default base constructor implicitly, you have to make it explicit.
Implicitly? No, constructors are not inherited. Your class may explicitly call it's parent's constructor. But if you want your class to have the same constructor signatures as the parent class's, you must implement them.
For example:
public class A
{
public A(int someNumber)
{
}
}
// This will not compile becase A doesn't have a default constructor and B
// doesn't inherit A's constructors.
public class B : A
{
}
To make this work you'd have to explicitly declare the constructors you want B to have, and have them call A's constructors explicitly (unless A has a default constructor of course).
public class B : A
{
public B(int someNumber) : base(someNumber)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With