Why the constructor get called in the reverse order?
In the inhe开发者_JS百科ritance why the base class constructor get the call first why not the derived one??
To make sure the public or protected members of the base-class are properly initialized before they are used in the derived class.
To be precise, the derived-class constructor is run first with an implicit call to the base-class constructor inserted as the first statement in the body of the derived-class constructor by the compiler (assuming default no-arg constructors).
The derived class is created by extending the base class. It should be ensured that the base class members are properly initialized, before it can be extended in a derived class. Also, members initialized in derived class should not be overridden by base class.
Consider what could happen if it were the other way around. Let's imagine a user class with an _id
value. The _id
of 0 is a special values that represents a "guest" account (ignore the issues around "special values", firstly they aren't always a bad idea, and secondly this is just an example). The _id
can also not be changed after construction (which makes sense, if it could be changed its no longer really much of an identifier).
public class User
{
private readonly int _id;
public User(int id)
{
_id = id;
}
public int ID
{
get { return _id; }
}
public bool IsGuest
{
get { return _id == 0; }
}
}
Now consider an Admin class that subclasses from this. One of the rules of the Admin class is that a guest can never be an admin. This invariant should be enforced at all points the guest status can change, which in this case is only in the constructor:
public class Admin : User
{
public Admin(int id)
:base(id)
{
if(IsGuest)
throw new SecurityException("Guest users cannot be admins.");
}
}
If Admin
was constructed before User
then it would always throw this exception, as the test would always compare 0 with 0. If we had a different special value for guests then it would be even worse, and never throw the exception even when it should, and allow for a security issue.
Bear in mind also that the person writing the Admin
class need not have any knowledge of how User
works beyond what is documented about its public and protected interface. They could catch the issue above by adding their own test for whether id
is zero or not, but apart from this being a needless duplication of code, there's no reason why they should know how the IsGuest
check works, and it could be much more complicated than it is above, and perhaps perhaps proprietary, obfuscated and undocumented.
More generally, the whole concept of "constructing an Admin" makes no sense without the concept of "constructing a User" as something that has happened first, we can't make a more specialised type of X without making a X as a prerequisite.
What gets born first, the parent or the child?
精彩评论