First of all this is not a duplicate question.
I know the facts that:
- During inheritance, the order of execution of constructors will be in the same order as their derivation and order of execution of destructors will be in reverse order of their derivation.
- Also, we can call base class constructor explicitly using
base
keyword in constructor definition.
My question is : For my below code
class ClassA
{
public ClassA(int a)
{
Console.WriteLine("Parameterized Constructor of ClassA");
}
}
class ClassB : ClassA
{
public ClassB(int a)
{
Console.WriteLine("Parameterized Constructor of ClassB");
}
}
class ClassC : ClassB
{
public ClassC(int a)
{
Console.WriteLine("Parameterized Constructor of ClassC");
}
}
class Program
{
static void Main(string[] args)
{
ClassC classc = new ClassC(1);
Console.ReadLine();
}
}
I am getting the complie time error:
'ClassA' does not contain a constructor that takes 0 arguments
'ClassB' does not contain a constructor that takes 0 arguments
But when I Add the default constructors to both the classes as :
class ClassA
{
public ClassA()
{
Console.WriteLine("Default Constructor of ClassA");
}
public ClassA(int a)
{
Console.WriteLine("Parameterized Constructor of ClassA");
}
}
class ClassB : ClassA
{
public ClassB()
{
Console.WriteLine("Default Constructor of ClassB");
}
public ClassB(int a)
{
Console.WriteLine("Parameterized Constructor of ClassB");
}
}
class ClassC : ClassB
{
public ClassC()
{
Console.WriteLine("Default Constructor of ClassC");
}
public ClassC(int a)
{
Console.WriteLine("Parameterized Constructor of ClassC");
}
}
class Program
{
static void Main(string[] args)
{
ClassC classc = new ClassC(1);
Console.ReadLine();
}
}
I got the output as expected.
Default Constructor of ClassA
Default Constructor of ClassB
Parameterized Constructor of ClassC
SO does this means, During inheritance all base classes needs a parameterless constructor.
I didn't get any clear explanation for this yet. Please dont make this as duplicate and any good explanation is appreciated.