Simple C++ method question (overloading?)

  • Context: C/C++ 
  • Thread starter Thread starter zeion
  • Start date Start date
  • Tags Tags
    C++ Method
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
zeion
Messages
455
Reaction score
1
Hi,

If I have a method that takes in say 5 new variables and assigns 5 class variables to these new values, and I only wanted to change one of these variables, is it possible to reuse this method and only have it take in say 1 new variable and change one class variable without having to write different methods for changing each individual variable?

ie.

class testClass
{
void changeFive (int first, second, third, fourth, fifth)
{
testClassFirst = first;
testClassSecond = second;
...
}

void changeOne (int first)
{
testClassFirst = first;
}
}
 
Physics news on Phys.org
Two different methods can share the same name (overloading), but other than a common name, they are different methods.
 
Last edited:
zeion said:
Hi,

If I have a method that takes in say 5 new variables and assigns 5 class variables to these new values, and I only wanted to change one of these variables, is it possible to reuse this method and only have it take in say 1 new variable and change one class variable without having to write different methods for changing each individual variable?

ie.
Code:
class testClass
{
void changeFive (int first, second, third, fourth, fifth)
{
   testClassFirst = first;
   testClassSecond = second;
   ...
}

void changeOne (int first)
{
   testClassFirst = first;
}
}
Assuming the 5 class variables are all int, this should work.

Code:
void changeVar(int *pl, int r)
{
       *pl = r;
}

You would call it as
Code:
changeVar(&testClassFirst, first);
changeVar(&testClassSecond, second);
etc

Though I am not sure how this helps you.
 
Last edited:
You can write it like this

class testClass
{
void changeFive (int first, second, third, fourth, fifth)
{
testClassFirst = first;
testClassSecond = second;
...
}

void changeFive (int first)
{
testClassFirst = first;
}

void changeFive (int first, int second)
{
testClassFirst = first;
}

void changeOne (int first)
{
testClassFirst = first;
}

void changeOne (int first)
{
testClassFirst = first;
}

phiby's suggestion of using the following is where I would go
void changeVar(int *pl, int r)
{
*pl = r;
}