Matt
Matt

Reputation: 4602

Best practice constructor with parameters in inherited classes

I have following easy class design, where myObject is importing for BaseClass.

public abstract class BaseClass
{
    public BaseClass(myObject parameter)
    {
        // ...
    }   
}

public class ChildClass : BaseClass
{

}

My problem is now, that I want to make my program extensible by inheriting from public BaseClass. So you could create a constructor

public ChildClass() :base(new myObject()){...}

which will lead to failures. Is there a possibilty to prevent inherited classes with own constructors? I actually would like to avoid constructors for ChildClass at all. Is this possible? Then I could use a factory and provide an Initialize method. Or is this something impossible, where I simply must be aware of and check in my code=

Upvotes: 0

Views: 648

Answers (1)

D Stanley
D Stanley

Reputation: 152556

Classes are completely responsible for their own constructors. They aren't inherited, and every class must have a constructor. So no, there's nothing you can do to "control" what constructors a base class can or can't have.

Upvotes: 4

Related Questions