What should we do that if we create an object of child class then the parameterized constructor of base class must be invoked?
To ensure that the base class's parameterized constructor is invoked when creating an object of the child class, you need to explicitly call the base class's constructor from the child class's constructor using the base keyword.
Here's an example to demonstrate this in C#:
using System;
class Animal
{
public Animal(string type)
{
Console.WriteLine($"Base class constructor with type: {type}");
}
}
class Dog : Animal
{
public Dog(string name) : base("Dog")
{
Console.WriteLine($"Child class constructor with name: {name}");
}
}
class Program
{
static void Main(string[] args)
{
Dog myDog = new Dog("Buddy");
}
}
Output:
Base class constructor with type: Dog
Child class constructor with name: Buddy
In this example, the 'Dog' class inherits from the 'Animal' class. The 'Dog' class's constructor calls the base class's parameterized constructor using base("Dog") to ensure that the base class's constructor is invoked. This initializes the 'Animal' part of the 'Dog' instance before the 'Dog' constructor initializes the 'Dog' part.
By explicitly calling the base class's constructor with appropriate arguments, you can control the initialization process and make sure that the necessary parts of the class hierarchy are properly set up.