-2

I have some confusion regarding constructor when inheritance is used:

i have following code :

 class Program 
    {
        static void Main(string[] args)
        {
            ClassD obj = new ClassD(10);
            Console.ReadLine();
        }
    }
    class ClassA
    {
        public ClassA(int a)
        {
            Console.WriteLine("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 ClassD : ClassC 
    {
        public ClassD(int a)
        {
            Console.WriteLine("Parameterized Constructor of ClassD");
        }
    }

when i write above code.. compiler generated 3 error saying :

'ClassA' does not contain a constructor that takes 0 arguments  

'ClassB' does not contain a constructor that takes 0 arguments  

'ClassC' does not contain a constructor that takes 0 arguments  

so why these errors throwing ?? is it necessary to have default constructor in base class.

what if i dont want default constructor in base class but want to have default constructor in derived class ?

ghanshyam.mirani
  • 3,075
  • 11
  • 45
  • 85

1 Answers1

1

so why these errors throwing ??

It's not throwing errors. The compiler is showing compilation errors. It's doing this because there isn't a default constructor on the base class and your derived classes are calling the base class with the parameter it requires.

is it necessary to have default constructor in base class.

No.

what if i dont want default constructor in base class but want to have default constructor in derived class ?

Then you provide a default constructor in the derived class but it must still call the base class and provide the parameters required by the base class constructor.

public ClassB() : base(0) // Or whatever value you want here for this default constructor
James Adkison
  • 9,412
  • 2
  • 29
  • 43