1

I read everywhere that :

Constructors do not inherit from base class to derived class

If this is true then

How can a base class default constructor call when we create object of derived class?

For example :

public class A
{
    public void AA()
    {
        //anything
    }
}

public class B : A
{
    public void BB()
    {
        //anything
    }
}

class Program
{  
    static void Main(string[] args)
    {

        B Bobject = new B(); // Why it will call class A's default constructor if constructors not inherit from base to derived class
    }
}
Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40
Sometimes Code
  • 591
  • 3
  • 14
  • 33
  • They're not inherited, but they can (and should) still be called from child-class constructors to initialize the parent. – Niko Sep 27 '14 at 19:56
  • http://msdn.microsoft.com/en-us/library/ace5hbzh.aspx – RenniePet Sep 27 '14 at 19:58
  • The default constructor is called to construct the base. If you don't want to use the default constructor within a derived class you can use the `:base(parameter)` syntax to force calling a different constructor. – Peter Ritchie Sep 27 '14 at 20:04

3 Answers3

1

You can look into IL generated by the C# compiler. This is generated for B constructor:

B..ctor:
IL_0000:  ldarg.0     
IL_0001:  call        A..ctor
IL_0006:  nop         
IL_0007:  nop         
IL_0008:  nop         
IL_0009:  ret  
Sergey Mozhaykin
  • 192
  • 1
  • 10
1

The default parameterless constructor of a base class will always be called implicitly. If your base class has no parameterless constructor then your derived class must call that constructor and provide the necessary parameters.

See Will the base class constructor be automatically called?

So to answer your question no, the constructor of a base class is not inheritered, but will be called one way or another, either by your derived class constructor or implicitly when you use the new keyword.

Community
  • 1
  • 1
James_F
  • 66
  • 6
0

The why:

In your example B IS-A A, that being it is an extension of an A. Given that, for B to be constructed the A bit must be constructed before B, otherwise B wouldn't be able to access and of the functionality provided by A.

The how is supplied by Sergey Mozhaykin's answer.

You can prove this by adding a non-default constructor to A (thus removing the default, parameterless one), the code will not compile because B no longer knows how to construct an A.

Community
  • 1
  • 1
BanksySan
  • 27,362
  • 33
  • 117
  • 216