C ++ change private member variable from static member function

While reading the code, I noticed that I have a static member function that changes the private member of a class through a pointer to an instance of the specified class.

It compiles and functions without problems, but I just wanted to know if it was kosher to edit a private variable in this way, from an element but a static function, or if I should use the public setVar function.

Please note that I am not trying to circumvent the standard coding practice by editing member variables from a static function - the function is necessarily static, so it can be run as a thread using the POSIX pthread library.

Cheers, Wyatt

+4
source share
2 answers

Yes it really is.

Although in most cases, having a non-static member is better, static members are sometimes used in cases where you need to pass a pointer to an external library, for example, in your case for the pthread library.

If it makes sense to change this private variable in other situations, and if you want to separate your class from the fact that it uses the pthread library, you can split the class into two:

  • one class that handles functionality (e.g. your class)
  • one class that handles interaction with pthread

The second class will then set the variable in the first class using the public method.

Example: this is probably your source code:

class MyClass { public: static void someMethod(MyClass *); private: type myMember; }; 

and you can also write it:

  class MyClass { public: void setMember(type value) {myMember = value; /* other other logic */} private: type myMember; } class MyClassPThreadInterface { public: static void someMethod(MyClass *myclass) {myclass->...();} } 

Thus, you completely separate your class from the fact that it is used by the PThread library. This makes it suitable for use in other cases (where the static method is rather pointless), and it is also easy to add another stream library (for example, Windows threads) without polluting the source class.

+4
source

Yes. private means that access is restricted by class.

0
source

Source: https://habr.com/ru/post/1314931/


All Articles