We have two classes’ base class and child class. A is the base class and B is the child class, If we create an instance of child class then which class’s constructor called first?
When you create an instance of a child class, the constructor of both the base class and the child class will be called. The constructor of the base class is invoked before the constructor of the child class. This is because the child class relies on the base class to set up its inherited properties and behavior before adding its own unique characteristics.
Here's the sequence of events when you create an instance of the child class 'B':
1. The constructor of the base class 'A' is called.
2. After the base class constructor finishes executing, the constructor of the child class 'B' is called.
This ensures that the child class has a consistent and complete state, including the properties and behavior inherited from the base class, before it adds its own specific features.
Here's a simple code example in C# to illustrate this:
using System;
class A
{
public A()
{
Console.WriteLine("Constructor of base class A");
}
}
class B : A
{
public B()
{
Console.WriteLine("Constructor of child class B");
}
}
class Program
{
static void Main(string[] args)
{
B bInstance = new B(); // Creating an instance of the child class B
}
}
Output:
Constructor of base class A
Constructor of child class B
In this example, you can see that the constructor of the base class 'A' is called before the constructor of the child class 'B'.