C# inheritance and default constructors

C#OopConstructor

C# Problem Overview


Suppose there is a base class A and a class B derived from A. Then, we know that the constructor of class A is never inherited by class B. However, when a new object of B is created, then - the default constructor of the class A is called prior to the default/custom constructor of class B is invoked. Maybe the purpose of this is that the fields of class A need to be initialized to default values.

Now, suppose that class A has defined a custom constructor. This means that the default constructor of class A is silently removed by the compiler. Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B's constructor? (How does the class A fields get initialized in such a case?)

C# Solutions


Solution 1 - C#

> Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B constructor?

The code will fail to compile, basically. Each constructor has to chain to another constructor, either implicitly or explicitly. The constructor it chains to can be in the same class (with this) or the base class (with base).

A constructor like this:

public B() {}

is implicitly:

public B() : base() {}

... and if you don't specify a constructor at all, it will be implicitly added in the same way - but it still has to have something to call. So for example, your scenario:

public class A
{
    public A(int x) {}
}

public class B : A {}

leads to a compiler error of:

> error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'A.A(int)'

However, you can specify a different constructor call explicitly, e.g.

public B() : base(10) {} // Chain to base class constructor

or

public B() : this(10) {} // Chain to same class constructor, assuming one exists

Solution 2 - C#

Once you provide your own constructor to class A, no automatic invocations happens during the class B object creation.

The first line in your class B constructor should be super(paramsToClassAConstructor) or it can be call to another constructor with in the class B using this(). It is the responsibility of the second constructor in class B to call the class A constructor in such case.

Solution 3 - C#

When a constructor completes execution - the object is in a valid initial state. We are supposed to use objects which are valid.
When we provide a non-default constructor for class A - we are effectively saying - to construct class A object i.e. to be in the valid initial state - we need more information - which is provided by the parameters.
Given this, the compiler helps by not generating the default constructor. The client code will fail to compile (as it should - how else will we make the object land in a valid state?) - and the client programmer would have to sit up and take notice.
When you provide an explicit empty constructor - you are effectively telling the compiler - I know what I am doing - the default constructor would most probably initialize the fields to some sensible default values.
Or to promote reuse - the default constructor can call the non-default one with some default values.
A subclass knows about its super class - a sub-class constructor can invoke super class methods - (some commonly reused methods in sub-classes). Given the above - this requires that the super class part should be in a valid state - i.e. its constructor was executed prior to any of its method invocation. This necessitates calling the super constructor before the sub-class constructor.
Given this - you will easily be able to design your constructor to enforce the correct initial state behavior.

Solution 4 - C#

There is no special rule for defining base class parameter constructors. Rules are same as other class constructors. You can define number of constructor as follows:

class baseclass
    {
        public baseclass()
        {
            
        }
        public baseclass(string message)
        {
            
        }
    }

If base class has constructor then child class or derived class are required to call the constructor from its base class.

class childclass : baseclass
    {
        public childclass()
        {
        }
        public childclass(string message)
            : base(message)
        {            
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhelloworldView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Bhargav Kumar RView Answer on Stackoverflow
Solution 3 - C#atulView Answer on Stackoverflow
Solution 4 - C#Neh18View Answer on Stackoverflow