If base class and child class both have constructor which one will be called first, when derived class object is created?

In C#, when a derived class object is created, the constructor of the base class is called first, followed by the constructor of the derived class. This is the same order of constructor calls as in other object-oriented programming languages, such as Java and C++.


The following code shows an example of the order of constructor calls in C#:

C#
class Base
{
    public Base()
    {
        Console.WriteLine("Base constructor called");
    }
}

class Derived : Base
{
    public Derived()
    {
        Console.WriteLine("Derived constructor called");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Derived derived = new Derived();
    }
}

When the code in Main() is executed, the following output will be displayed:

Code snippet
Base constructor called
Derived constructor called

As you can see, the constructor of the base class is called first, followed by the constructor of the derived class.

The order of constructor calls is important because it ensures that the members of the base class are initialized before the members of the derived class. This is necessary because the members of the derived class may depend on the members of the base class.

For example, if the base class has a member variable called name, and the derived class has a member function that prints the value of name, the member function of the derived class will not be able to print the value of name until the constructor of the base class has initialized name.

Post a Comment

Previous Post Next Post