I am new to C# and .Net, I have following code where I'm getting error while compiling in C# visual Studio 2022. Can someone kindly explain what am I doing wrong and how can I rectify it?
class Vehicle
{
public string company; //class field
public void ignition() //class method
{
Console.WriteLine("Vroom Vroom");
}
public Vehicle (string companyName) //class parameterized constructor
{
company = companyName;
}
}
class Car : Vehicle
{
public string model; //class field
public Car (string modelName) //class parameterized constructor //this is where the error occurs
{
model = modelName;
}
}
CodePudding user response:
To fix, the derived class should call base
public Car (string modelName) : base(modelName)
But in your case, design is not good enough. Potential fix is
class Car : Vehicle
{
public string model; //class field
public Car (string modelName, string company) : base(company) //class parameterized constructor //this is where the error occurs
{
model = modelName;
}
}
The concept is that if you have explicit constructor in the base class, you must use that. Unless you explicitly define the parameter-less constructor. So, you need to pass your company through derived class constructor to the base class.