Sometimes Code
Sometimes Code

Reputation: 601

Constructor and inheritance

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
    }
}

Upvotes: 1

Views: 129

Answers (3)

BanksySan
BanksySan

Reputation: 28500

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.

Upvotes: 0

James_F
James_F

Reputation: 66

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.

Upvotes: 1

Sergey Mozhaykin
Sergey Mozhaykin

Reputation: 192

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  

Upvotes: 1

Related Questions