views:

196

answers:

5

In base class constructors I always see a parameterless constructor, like so:

   public abstract BaseClass {...
protected BaseClass() { }
...}

but is it acceptable design to include a parameter in the base class constructor?

   public abstract BaseClass {...
protected BaseClass(string initObj) { }
...}
+12  A: 

Yes, it is acceptable for a base class to require a parameterized constructor. This simply imposes a requirement that any classes which inherit must provide a value to the base constructor.

Joel Martinez
Wow, fast response. Now I can continue coding...
T. Webster
+1  A: 

In most cases the derived classes have some form of parameterized constructors. So when those constructors are called they can still call the parameterless base constructor:

public employee(int age) : base(this)

The answer is if you need one just add one, there is nothing wrong with that. Think of a business object base class that requires some validations to say a phone number or email address. You want to ensure the derived classes get these business rules loaded into them. If you did not have the base class constructor you could not add these rules to your derived class objects.

JonH
+2  A: 

It is a good practice if the object cannot be used or has dependencies on every method on this class. For instance, if you have a class that have the same parameters in all the functions, it would be better to set that in the constructor, so the function signature is smaller.

jpabluz
The purpose would be to assign the constructor parameter to a property that will be inherited through the inheritance hierarchy. Every derived class will be expected to depend on this property. At the very least, I want to declare that there is a dependency on this object.
T. Webster
+2  A: 

What the writer of the base class is doing in your first example is just making sure that no public constructors are exposed. Probably the base class needs nothing special in the constructor but, if you don't write any, the compiler will add the default (parameter-less) constructor for you.

Not that I think this is specially useful. You cannot instantiate an abstract class anyway.

Gorpik
+1  A: 

Yes, its a perfectly acceptable design decision, only it must make sense for the base class - presumably to initialise its own members from the parameter. Also, it imposes a restriction on derived classes: either they must pass in a literal, or impose a similar restriction on their clients or further derived classes.

quamrana