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?
Assuming from the context that the "do something on B" functions only operate on the B
member and not other state in A
then:
B
then they should be members of B
.A member function is a member function because its' scope has access to the member variables without having to use referencing and pointer syntax. As someone mentioned earlier this would most likely make it simpler to code and maintain so you would use this method unless you needed the function to be a free function that might take the same type data but from different classes in which case you would have to pass by reference or use pointers to gain access to the scope of the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With