No, It will not create object of base class. But, when a derived class object is created, the constructors from the base and derived classes will run. The order in which they run is important, too -- the base class constructor runs first, then the derived.
class Program { static void Main(string[] args) { var x = new B(); } } public class A { public A() { Console.WriteLine(1); } } public class B : A { public B() { Console.WriteLine(2); } }
If we are considering the above case, we can expect an output like below
1 2
one exception there is, If we have static constructor in place then it will get executed first and that is in the reverse order, that means first the derived class static constructor will get executed and then base class static constructor.
class Program { static void Main(string[] args) { var x = new B(); } } public class A { public A() { Console.WriteLine(1); } static A() { Console.WriteLine(2); } } public class B : A { public B() { Console.WriteLine(3); } static B() { Console.WriteLine(4); } }
If we are considering the above example, We can expect an output like below.
4 // derived class static constructor called 2 // base class static constructor called 1 // base class constructor called 3 //derived class constructor called
Back to your question, the reason why the base class constructor is created during derived class object creation is :
when we inherit one class from another, the data members and member functions of base class comes automatically in derived class based on the access specifier, but the definition of these members exists in base class only. So when we create an object of derived class, all of the members of derived class must be initialized but the inherited members in derived class can only be initialized by the base class’s constructor as the definition of these members exists in base class only. This is why the constructor of base class is called first to initialize all the inherited members.