I want to clear my understanding of this basic OOPS concept in c#. On most of the internet sites, I read that a derived class inherits the private members o
It would be helpful if there were a means by which a class could specify that for every parent-class constructor, the system should infer the existence of a child-class constructor with the same signature and access which does nothing but process field initializers and chain to the corresponding base constructor. Having such a feature available by specific request would be unlikely to cause bugs; even having that be the inference when a derived class doesn't specify any constructors (as opposed to only inferring a parameterless constructor that chains to a base parameterless constructor) would probably be pretty safe if that were a language design feature (adding such a feature to an existing framework, however, would be a bad idea, since the authors of derived classes which want to expose a parameterless constructor but not any parameterized ones might not have included any constructor, with the expectation that the compiler would infer the parameterless constructor only).
If a derived class has any non-trivial constructors of its own, however, it is likely that the child class does not intend for any object to be created without going through one of them. Suppose a parent class has only a parameterized constructor and someone writes:
class Child : Parent
{
Thing blah;
Child()
{
blah = new Thing();
}
}
Every Child
which is is created will have blah
set to a new thing. Now suppose a new version of the base class adds a Name
property, and adds a constructor which specifies the name. If constructors were auto-inherited, then code which said myChild = new Child("Fred");
would chain through to the constructor of Parent
, but never set blah
to a new Thing
.
Safe constructor "inheritance" might be made possible if a class could specify a that every instance should be produced by chaining to a parent constructor and then executing a specified block of code to establish child-class invariants. Such a feature would be somewhat complicated to implement, however, and it's unclear that it would be worth the cost.