Why does C # not inherit constructor from base class

Possible duplicates:
Constructors and Inheritance
Why are constructors not inherited?

When defining a class inherited from the base class, I must override all its constructors. I am wondering why C # doe snot supports inheritance from base class constructors?

+4
source share
3 answers

Constructors are not inherited, because we cannot correctly determine how to create objects of a derived class. When all derived classes will use parent constructors implicitly, this will be a problem in my solution, because if we forgot to override the constructor, the object might not be initialized correctly. If you want the constructor of the derived class to do the same thing as the constructor of the parent class, call it with base .

Also remember that the constructor of the base class (without parameters) starts automatically if you do not call any other constructor of the base class, the arguments are explicit. Therefore, calling base() is redundant .

+12
source

Only member variables and member methods can be inherited from one class to a derived one.

+2
source

The constructor of the derived class implicitly calls the constructor for the base class or superclass in Java terminology. In inheritance, all constructors of the base class are called before the constructors of the derived class in the order in which the classes appear in the class hierarchy.

Now, if the base class has more than one constructor, then the derived class must determine which one should be called. For instance:

 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, visit: http://msdn.microsoft.com/en-us/library/ms228387(v=vs.80).aspx

+1
source

Source: https://habr.com/ru/post/1333547/


All Articles