This practice is somewhat questionable, so you might want to rethink your approach here.
If you still want to go ahead with this, the correct way is to have a virtual
method that provides this value to the base constructor:
class Base
{
public Base()
{
obj = new ObjNeedParam(GetParamVal());
}
protected virtual int GetParamVal() { return 1; }
}
class Derived : Base
{
protected override int GetParamVal() { return 2; }
}
You will have to ensure that the override
does not use any class members of Derived
that get initialized in Derived
's constructor because that constructor will not have run yet at the point where the override is called! See Virtual member call in a constructor.
Update: It is somewhat questionable because when constructing an object of some derived type the compiler has a problem to solve: in what order should the fields be initialized and the constructors run so that any method call from inside any constructor is guaranteed to find the object in a "usable" state?
This problem cannot be solved in the general case because by definition the object is not in a usable state until all constructors have returned, and we are talking about calling methods from inside these constructors. So the compiler has to guarantee as much as it can and either prevent or allow you to do things that are not provably safe.
In this scenario C++ (amusingly) prevents the doing of things that are not provably safe, while C# allows it. Therefore it's somewhat questionable because if you don't pay attention it is possible to introduce bugs. A safer approach would be to write the class such that this member is initialized after the constructors have run.