Reputation: 3
I have a class which I intend to use for performing calculations. I declare one static object of the class elsewhere which I use to obtain results. The class has one public function apart from the constructor.
public:
double getProbability(PlayerStats &p1, PlayerStats &p2, Score &score);
As you can see, I have three objects as input parameters. My class then has two private functions which are called from getProbability()
. One requires p1
and p2
, the other requires all three of the parameters
My question is this. Is it better to pass these objects as parameters to the function or is it better to create private member variables and use these.
So for example
double MyClass::getProbability(PlayerStats &p1, PlayerStats &p2, Score &score){
otherFunction(p1,p2);
anotherFunction(p1,p2,score);
....
}
or
double MyClass::getProbability(PlayerStats &p1, PlayerStats &p2, Score &score){
this->p1 = p1;
this->p2 = p2;
this->score = score;
otherFunction(); //use member variables in these functions
anotherFunction();
....
}
Upvotes: 0
Views: 171
Reputation: 11699
You should pass the arguments directly to your other methods. Even if other functions used them it would be very confusing because nothing in the function signature indicates that those arguments would be kept around.
If you need some of these parameters in other functions and those parameters remain the same through several calls, you could refactor your class. It would take the ones which stay the same in the constructor and then function calls just pass in the ones which will change. It really depends on the needs of your application to determine whether this is a better approach.
Upvotes: 0
Reputation: 8437
I prefer passing the parameter to the private functions. As far as your class may be access by multiple concurrent threads, it is better to send each data to its related function.
Upvotes: 2
Reputation: 96301
It's better to pass them as parameters, as they don't really represent class state and storing them as members will probably be more performance costly than simply continuing to pass around the references.
But it doesn't really look like your class has any state at all, which leads me to believe all of these methods should be free-functions in a suitable namespace rather than members of a class (perhaps you come from a Java background?).
Upvotes: 4