How does initializing inherited members inside base class constructor reduce the calls to…?

Posted by flockofcode on Stack Overflow See other posts from Stack Overflow or by flockofcode
Published on 2010-06-17T19:45:38Z Indexed on 2010/06/17 19:53 UTC
Read the original article Hit count: 360

Filed under:

I’ve read that instead of initializing inherited members ( _c1 in our example ) inside derived constructor:

class A
{
    public int _c;
}

class B:A
{
    public B(int c)
    {
        _c = c;
    }
}

we should initialize them inside base class constructor, since that way we reduce the calls to inherited members ( _c ):

class A
{
    public A(int c)
    {
        _c = c;
    }
    public int _c;
}

class B:A
{
    public B(int c)
        : base(c)
    {


    }
}

If _c field is initialized inside base constructor, the order of initialization is the following:

1) First the field initializers of derived class B are called
2) Then field initializers of base class A are called (at this point _c is set to value 0)
3) B’s constructor is called, which in turn calls A’s custom constructor
4) _c field gets set to value of a parameter c ( inside A’s custom constructor )
5) Once A’s custom constructor returns, B’s constructor executes its code.

If _c field is initialized inside B's constructor, the order of initialization is the following:

1) First the field initializers of a derived class B are called
2) Then field initializers of a base class A are called(at this point _c is set to value 0)
3) B’s constructor is called, which in turn calls A’s default constructor
4) Once A’s custom constructor returns, B’s constructor sets _c field to a value of parameter c

As far as I can tell, in both cases was _c called two times, so how exactly did we reduce calls to inherited member _c?

thanx

© Stack Overflow or respective owner

Related posts about c#