So, at school we got an assignment to make a car in OOP, until now its been pretty easy and straight forward. But now I need to create four constructors, one with no parameters, two with one parameter and one with two parameters.
As far as I know the way overloading works is that it checks the amount of parameters you supply it with and then checks which constuctor it has to use. As two of the constructors are the same, both accepts ints, only one needs to change the amount or gears, and the other needs to change the maximum speed.
Is there a way to do this without passing an extra parameter?
No, overloading isn’t based solely on the number of parameters – it’s based on their types too.
However:
That’s a problem. You can’t declare two constructors like this:
Those signatures clash as far as overloading is concerned.
I would suggest having public static factory methods, so you can specify what you’re trying to create:
You’d then possibly have one constructor which accepted both values, and default whichever one’s missing when you call the constructor from the factory method.
However, there are two other oddities in your description:
EDIT: Okay, now we know a bit more, here’s the sort of thing I mean:
Note that you could use optional parameters and named arguments for this too in C# 4:
Then:
I wouldn’t recommend that in general though – certainly not while you’re still relatively new to the language. There are various subtleties around optional parameters.