Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you pass member variables within member functions?

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?

like image 241
Aurelius Avatar asked Aug 12 '14 23:08

Aurelius


2 Answers

Assuming from the context that the "do something on B" functions only operate on the B member and not other state in A then:

  • If the functions directly manipulate/operate on the private state of B then they should be members of B.
  • Else they should be free functions.
like image 153
Mark B Avatar answered Sep 29 '22 09:09

Mark 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.

like image 45
Rod Gaskins Avatar answered Sep 29 '22 11:09

Rod Gaskins