
.NET 1.1+C# Inheritance and Constructors
The nineteenth part of the C# Object-Oriented Programming tutorial continues the discussion of inheritance. Constructor and destructor functionality is not inherited by subclasses but these can still use the constructors defined in their base class.
Inheritance
In the previous part of the C# Object Oriented Programming tutorial, we examined the concept of inheritance and its application in C#. Using inheritance, methods, properties, events, indexers, operators and internal variables that are declared in a base class are automatically made available to its subclasses.
Constructors and Inheritance
Unlike the above class behaviour, constructors that are declared within a base class are not inherited by subclasses. As with any other class, a subclass with no constructors defined is provided with a default constructor that provides no explicit functionality. The constructors from the base class are not made available when creating new subclass object instances.
When a subclass is instantiated, the standard behaviour is for the default constructor of the base class to be called automatically. In this way, the base constructor can initialise the base class before the subclass' constructor is executed.
To demonstrate the order of execution of the constructors, examine the following sample code. The first class is the main Program class within a console application. It simply instantiates a MySubclass object. MyBaseClass is a class with a single constructor that outputs a message to the console. MySubclass inherits from MyBaseClass and also outputs to the console when constructed. Note the order in which the messages appear.
class Program
{
static void Main()
{
MySubclass test = new MySubclass();
}
}
class MyBaseClass
{
public MyBaseClass()
{
Console.WriteLine("MyBaseClass constructor called.");
}
}
class MySubclass : MyBaseClass
{
public MySubclass()
{
Console.WriteLine("MySubclass constructor called.");
}
}
/* OUTPUT
MyBaseClass constructor called.
MySubclass constructor called.
*/
This behaviour is repeated for complex hierarchies of inherited classes. Where there are more than two levels of inheritance, the least specialised class' constructor is called first with each constructor down the tree called in turn until the specifically instantiated class' constructor is finally executed.
29 March 2008