Why do you define a constructor with parameters and the default constructor without parameters disappears?

Asked 2 years ago, Updated 2 years ago, 95 views

If you create a constructor with parameters in C#, C++, and Java, the default constructor without parameters disappears. Before, I thought it was just like that, but I suddenly became curious about why?

What's the reason for this? Is this just a safety precaution, "I've already created a generator, so I probably don't need any default generator like this?" Or is there a technical reason why adding one constructor prevents the compiler from making it?

c++ java c# default-constructor

2022-09-21 20:11

1 Answers

There is no technical reason why the compiler cannot add a constructor just because the user defines it. However, if you want to instantiate a class in a non-static class that does not define a constructor, the compiler does nothing, but you must add a default constructor that can be instantiated. So it doesn't have to include an empty constructor to make my code work.

If you define a constructor with one or more parameters, you can use this constructor to initialize the contents of the class when you instantiate the class, and if the compiler defines a default constructor at random, it increases the likelihood that someone will skip this logic and create a bug. If you need a default constructor, it is preferable to explicitly define a default constructor.


2022-09-21 20:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.