Home > Software design >  Is there a shortcut to write a function with the same definition but different prototypes?
Is there a shortcut to write a function with the same definition but different prototypes?

Time:04-16

I have a method of a class which basically looks like this:

void MyClass::method() {
    // Here I'm just doing something with parameters which are class attributes
    parameter_3 = parameter_1   parameter_2
}

I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call:

void MyClass::method(type1_t parameter_1, type2_t parameter_2);

I do not want to repeat the same code in another definition. What are possible solutions? The less ugly the better.

CodePudding user response:

I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call:

This can be solved using delegation. Simply call one overload from the other. Example:

void MyClass::method(type1_t parameter_1, type2_t parameter_2) {
    parameter_3 = parameter_1   parameter_2;
}

void MyClass::method() {
    method(parameter_1, parameter_2);
}
  • Related