Samuel
Samuel

Reputation: 640

How to pass two values from one function to another in the same class?

I have this function:

void fraction::init()
{
  cout<<"enter the values for the numerator and denominator\n";
  cin>>num;
  cin>>denom;
}

and I want these two numbers to be used in another function that manipulate them. how do I take them to this other function? NOTE:both functions are of the same classs.

Upvotes: 1

Views: 303

Answers (3)

Apoorv Ashutosh
Apoorv Ashutosh

Reputation: 4024

Either make them members of the class, as so many suggest, or you could try passing them when needed. If you want their values to reflect changes, pass them by reference.

datatype function1(int *a, int *b)

And then when you call them from init() function,

function1(&num, &denom)

Hope this helps

Upvotes: -1

Gorpik
Gorpik

Reputation: 11038

It depends on how you will be using those functions. Since both belong to the same class, you can make num and denom (private) members of the class. But you can also use references if those values come from outside the class. This will work regardless of the functions belonging to the same class or not:

class fraction
{
public:
  void init(int& num, int& denom) const;
  void otherFunction(int num, int denom);
}

void fraction::init(int& num, int& denom) const
{
  cout<<"enter the values for the numerator and denominator\n";
  cin>>num;
  cin>>denom;
}

// Define otherFunction() appropriately

Then use those functions in another piece of code:

// ...
int aNum, aDenom;
fraction fr;
fr.init(aNum, aDenom);
fr.otherFunction(aNum, aDenom);
// ...

Upvotes: -1

Andreas Fester
Andreas Fester

Reputation: 36649

Simply define them as members of the class:

class fraction {
private:
  int num;
  int denom;

public:
   void init();          // has access to num and denom
   void otherMethod();   // also has access to num and denom
};

You should also not rely on init() being called to initialize the variables with a default value, and you should also not rely on the various default initializations provides by C++, see Default variable value.

Instead, add a constructor which sets default values for the variables to make sure that the variables have reasonable values after an object of the class has been created. Then, you can still call init() to set whatever values you want (and probably you should rename init() to something like readValues() to reflect what the method really does).

Upvotes: 5

Related Questions