Why does the default parameterless constructor go away when you create one with parameters

There’s no reason that the compiler couldn’t add the constructor if you’ve added your own – the compiler could do pretty much whatever it wants! However, you have to look at what makes most sense:

  • If I haven’t defined any constructor for a non-static class, I most likely want to be able to instantiate that class. In order to allow that, the compiler must add a parameterless constructor, which will have no effect but to allow instantiation. This means that I don’t have to include an empty constructor in my code just to make it work.
  • If I’ve defined a constructor of my own, especially one with parameters, then I most likely have logic of my own that must be executed on creating the class. If the compiler were to create an empty, parameterless constructor in this case, it would allow someone to skip the logic that I had written, which might lead to my code breaking in all number of ways. If I want a default empty constructor in this case, I need to say so explicitly.

So, in each case, you can see that the behaviour of current compilers makes the most sense in terms of preserving the likely intent of the code.

Leave a Comment