Quote:
Original post by hpjchobbes
When dealing with a class that inherits from a base class, the document states: " Inheritance means that a class implicitly contains all members of its base class, except for the constructors of the base class". In the example, they show a Point3D class that inherits from a Point class. The Point3D's constructor inherits from the Point constructor. Does the inherited constructor ever get run? In the example, do X and Y not get values since the Point3D constructor didn't specify?
Think of a class hierarchy (A, B inherits from A, C inherits from B) as a tower. A would be the lowest level, C the highest. When building such a tower, the levels must be built in order: first level A, then B, then C. Same thing happens with constructors. First, one of A's constructors
must be called, then one of B's constructors, and lastly, one of C's.
So to answer your question: Point's constructor does get to run indeed, and it runs first.
public class Point3D: Point{ public int z; public Point3D(int x, int y, int z) : Point(x, y) // <----- { this.z = z; }}
The arrow points to the code which shows which of the base's constructors (there can be more than one due to overloading) needs to be called with what arguments. If that line were omitted, it would be interpreted as an implicit call to the default constructor (which structs always have, classes not necessarily).
Paragraph 10.10.1 in the spec explains fully how constructors are called.
As an example:
class A{ A() { ... } A(int x) { ... } A(string s) { ... }}class B : A{ B() { ... } // construction order: A(), B() B(int x) : base(x.ToString()) { ... } // order: A(string), B(int)}class C : B{ C() : base(5) { ... } // order : A(string), B(int), C() C(string s) { ... } // order : A(), B(), C(string)}
What it means for constructors not to be inherited (using the spec's Point example):
Point provides two constructors:
- one implicit default constructor taking 0 arguments and initializing x and y to 0
- one taking 2 integer arguments
Point3D provides two constructors: one with 0 arguments (x, y, z = 0) and one with 3 int-arguments.
If constructors were to be inhereted, Point3D would have a
third constructor: the one from Point taking 2 arguments. This is not the case.
[Edited by - SamLowry on July 1, 2007 4:02:33 AM]