Sort of a style question here. Say I have a class A
which has to do a sequence of reasonably complex things to its member variable B b
class A {
public:
void DoStuffOnB(){
DoThing1();
DoThing2();
DoThing3();
}
private:
B b;
void DoThing1(){ /* modify b */ }
void DoThing2(){ /* modify b */ }
void DoThing3(){ /* modify b */ }
};
where the DoThings
functions only depend on b
(or other member variables and some passed parameters). If I want to make those functions re-usable in the future outside of that class, I'm better off writing them as:
class A {
public:
void DoStuffOnB(){
DoThing1(b);
DoThing2(b);
DoThing3(b);
}
private:
B b;
void DoThing1(B& b){ /* modify b */ }
void DoThing2(B& b){ /* modify b */ }
void DoThing3(B& b){ /* modify b */ }
};
and then my DoThing
functions can just be copied elsewhere in the future. Am I better off writing the function to take all relevant parameters like that, or should the function only take non-member parameters?
In case the answer is "you should write the function to take all relevant parameters", why would one bother to put it in a class?
When should you use a free function, and when should you use a member function?
B
object then why would they even be a part of theA
class? Why not make them free functions (or part of theB
type)? Then you could call them from withinA
or outside ofA
. – Susetteb
? Is it possible to passb
toDoSTuffOnB()
rather than store it as a member variable at all? – VicentaA
to storeb
here. The larger scope of what I'm doing is some fairly involved initialization on the member variables ofA
based on some input. – KujawaA
to store a member variableb
, but theDoThingN()
methods only operate onb
, so they should be either free functions or member functions ofclass B
, and you should be invokingb.DoThing1()
, etc, inside your code forA
. Then you automatically pass theb
element to the functions, of course, but it is done behind the scenes. – HomeroomA
would have several instances ofB
that need to be modified. In general there are a bunch of member variables in A that need initializing. – Kujawa/* modify b */
in the OP's code, I did not assume that meant tampering with private members, but rather, calling non-const public member functions onb
. – Shamblesb
is a simple data structure. – Kujawa