Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Simple C++ method question (overloading?)

  1. Mar 17, 2012 #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;
    }
    }
     
  2. jcsd
  3. Mar 17, 2012 #2

    rcgldr

    User Avatar
    Homework Helper

    Two different methods can share the same name (overloading), but other than a common name, they are different methods.
     
    Last edited: Mar 17, 2012
  4. Mar 18, 2012 #3

    Assuming the 5 class variables are all int, this should work.

    Code (Text):
    void changeVar(int *pl, int r)
    {
           *pl = r;
    }
    You would call it as
    Code (Text):

    changeVar(&testClassFirst, first);
    changeVar(&testClassSecond, second);

    etc

    Though I am not sure how this helps you.
     
    Last edited: Mar 18, 2012
  5. Mar 18, 2012 #4
    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;
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Simple C++ method question (overloading?)
  1. Bisection method by c (Replies: 10)

Loading...