Inheritance & Constructors
The constructors and destructors are not inherited to a Derived class from a Base class. However when we create an object of the Derived class, the derived class constructor implicitly call the Base class default constructor. The following program shows this.
using System; class Base { public Base() { Console.WriteLine("Base class default constructor"); } } class Derived : Base { } class MyClient { public static void Main() { Derived d1 =new Derived();// Displays 'Base class default constructor' } }
Remember that the Derived class constructor can call only the default constructor of Base class explicitly. But they can call any Base class constructor explicitly by using the keyword base.
using System; class Base { public Base() { Console.WriteLine("Base constructor1"); } public Base(int x) { Console.WriteLine("Base constructor2"); } } class Derived : Base { public Derived() : base(10)// implicitly call the Base(int x) { Console.WriteLine("Derived constructor"); } } class MyClient { public static void Main() { Derived d1 = new Derived();// Displays 'Base constructor2 followed by 'Derived Constructor'' } }
Note that by using base() the constructors can be chained in an inheritance hierarchy.