Sometime back I got a interview question, in inheritance class relationship, when you are trying to create a derived class instance which constructor will be invoked first?
Is it the base class constructor invoked first?
OR
Is it the derived class constructor invoked first?
Let's create a simple console application in C# language to demonstrate constructor invocation sequence/order:
{
class Program
{
static void Main(string[] args)
{
DerivedClass derivedClassObject = new DerivedClass();
Console.ReadKey();
}
}
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base Class Constructor invoked.");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("Derived Class Constructor invoked.");
}
}
}
Let's have a look at the C# sample code output below:
Base Class Constructor invoked. Derived Class Constructor invoked.
After analyzing the example's output we can say:
Base class constructor is invoked first and then the derived class constructor.
It make sense because during a building in under a construction, first basement will be built then the the floors.
Let's create a plain console application example to demonstrate destructor invocation order:
{
class Program
{
static void Main(string[] args)
{
DerivedClass derivedClassObject = new DerivedClass();
// Set the object to null and call
// the GC.Collect(), so that
// destructors are invoked.
derivedClassObject = null;
GC.Collect();
Console.ReadKey();
}
}
public class BaseClass
{
~BaseClass()
{
Console.WriteLine("Base Class Destructor invoked.");
}
}
public class DerivedClass : BaseClass
{
~DerivedClass()
{
Console.WriteLine("Derived Class Destructor invoked.");
}
}
}
Let's have look at the example output:
Derived Class Destructor invoked. Base Class Destructor invoked.
After analyzing the example's output it is clear that:
Derived class destructor is invoked first and then the base class destructor.
It make sense because when building is being demolished, similar to Garbage collection - the floors will be demolished first and then the basement.