If I have 2 constructors in my custom class and one of them takes an extra argument and does everything the first one does but with just one additional line of code (and this extra line utilises the extra argument), how best to deal with this without having to duplicate all the code in the first constructor?
Example code
public myConstuctor(int number, int number2){
int result = (number + number2);
int result2 = (number2 - number1)
//Etc
//Etc
//Etc
//Etc
}
public myConstructor(int number1, int number2, int number 3){
int result = (number + number2);
int result2 = (number2 - number1)
//Etc
//Etc
//Etc
//Etc
int result3 = (result + result2 + number3)
}
There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.
The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.
The C++11 delegating constructors reduce the code duplication and make effective use of the member initializer lists.
You can make the second constructor call the first one:
public MyClass(int number1, int number2, int number3) {
this(number1, number2);
You can call the other constructor and put all of your logic there.
public myConstructor(int number, int number2){
this(number, number2, 0);
}
public myConstructor(int number1, int number2, int number3){
int result = (number + number2);
int result2 = (number2 - number1)
//Etc
//Etc
//Etc
//Etc
int result3 = (result + result2 + number3)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With