Reputation: 29720
I am writing an abstract base class. I want all the classes that inherit from it to inherit a constructor that basically does the same things for all the classes. Is this possible?
Upvotes: 1
Views: 122
Reputation: 292405
If the abstract base class has a default constructor (i.e. a constructor with no parameters), it will automatically be called by the derived classes constructors, unless they explicitly call another constructor of the base class.
abstract class B
{
protected B()
{
...
}
protected B(object foo)
{
...
}
}
class D : B
{
public D()
: base() // not actually necessary, since it's called implicitly
{
}
public D(object foo)
: base(foo)
{
}
}
Upvotes: 2
Reputation: 8452
Doing your constructor protected will do the stuff
public abstract class A
{
protected A(string v) { V = v; }
public string V { get; protected set; }
}
public class AA : A
{
public AA(string v) : base (v) {}
}
Upvotes: 2
Reputation: 584
In your derived classes constructor, you will need to call your base constructor like so:
base(param1,param2,...)
If you do not call the base constructor explicitly, the default constructor in the base class will be called, if one exists. If not, you will get a compile error.
Upvotes: 0