Possible Duplicates:
Constructors and Inheritance
Why are constructors not inherited?
When define class inherited from base class, I have to redefine all its constructors. I am wondering why C# does not support inherit from base class's constructors?
Constructors are not inherited because we wouldn't be able to properly determine how our derived class objects were instantiated. When all derived classes would use parent's constructors implicitly, in my oppinion it would be a problem because if we forgot to redefine constructor, the object might have been initialized incorrectly. If you would like the derived class constructor to do the same as parent class constructor, call it using base.
Also be aware of the fact that the base class constructor (parameterless) is automatically run if you don't call any other base class constructor taking arguments explicitly. So calling base() is redundant
.
The constructor of the derived class implicitly calls the constructor for the base class, or the superclass in Java terminology. In inheritance, all base class constructors are called before the derived class's constructors in the order that the classes appear in the class hierarchy.
Now, if the base class has more than one constructor, then the derived class has to define which one should be called. For example:
public class CoOrds
{
private int x, y;
public CoOrds()
{
x = 0;
y = 0;
}
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
}
//inherits CoOrds:
public class ColorCoOrds : CoOrds
{
public System.Drawing.Color color;
public ColorCoOrds() : base ()
{
color = System.Drawing.Color.Red;
}
public ColorCoOrds(int x, int y) : base (x, y)
{
color = System.Drawing.Color.Red;
}
}
For more information please visit: http://msdn.microsoft.com/en-us/library/ms228387(v=vs.80).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With