views:

105

answers:

2

I noticed while reading through my code that I have a static member function which alters a private member of its class through a pointer to an instance of said class.

It compiles and functions without issue, but I just wanted to know whether or not it was kosher to edit a private variable in this way, from a member but static function, or if I should be implmenting a public setVar function.

Note that I'm not trying to bypass standard coding practice by editing member variables from a static function - the function is necessarily static so that it can be run as a thread using the POSIX pthread library.

Cheers, Wyatt

+2  A: 

Yes, this is valid.

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

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

  • one class that handles the functionality (like your class now)
  • one class that handles the interfacing to pthread

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

Example: this is probably your original code:

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

and this is how you could 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->...();}
    }

That way, you completely separate your class from the fact that it is being used by the PThread library. It makes it usable in other cases as well (where the static-method is rather pointless) and it is also easy to add another thread-library (e.g. Windows threads) without polluting the original class.

Patrick
A: 

Yes. private means that access is restricted to the class.

FredOverflow