During inheritance, base class may also contain constructor and destructor.
In this case if you create an instance for the derived class then base class constructor will also be invoked and when derived instance is destroyed then base destructor will also be invoked and 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.
Example Program
using System;
namespace ProgramCall
{
class Base1
{
public Base1()
{
Console.WriteLine("Base Class Constructor");
}
~Base1()
{
Console.WriteLine("Base Class Destructor");
}
}
class Derived1 : Base1
{
public Derived1()
{
Console.WriteLine("Derived Class Constructor");
}
~Derived1()
{
Console.WriteLine("Derived Class Destructor");
}
}
class ConstructorInheritance
{
static void create()
{
Derived1 obj = new Derived1();
}
static void Main()
{
create();
GC.Collect();
Console.Read();
}
}
}
Output
Base Class Constructor
Derived Class Constructor
Derived Class Destructor
Base Class Destructor
Note
During inheritance, if the base class contains only parameterized constructor, then derived class must contain a parameterized constructor even it doesn’t need one.
In this case while creating parameterized constructor in derived class, you must specify the parameters required for derived class along with the parameters required for base class constructor and to pass arguments to base class constructor, use the keyword “base” at the end of parameterized constructor declaration in derived class preceded with “:”.
Example Program
using System;
namespace ProgramCall
{
class Base2
{
int A, B;
public Base2(int X, int Y)
{
A = X;
B = Y;
}
public void PrintAB()
{
Console.Write("A = {0}\tB = {1}\t", A, B);
}
}
class Derived2 : Base2
{
int C;
public Derived2(int X, int Y, int Z)
: base(X, Y)
{
C = Z;
}
public void Print()
{
PrintAB();
Console.WriteLine("C = {0}", C);
}
}
class BaseParamConstructor
{
static void Main()
{
Derived2 obj = new Derived2(10, 20, 30);
obj.Print();
Console.Read();
}
}
}
Output
A = 10 B = 20 C = 30