Search code examples
c++syntaxfriendstatic-members

Declaring C++ static member functions as friends of the class in which it resides (syntax)


What is the syntax for declaring a static member function as a friend of the class in which it resides.

class MyClass
{
private:
  static void Callback(void* thisptr); //Declare static member
  friend static void Callback(void* thisptr); //Define as friend of itself
}

Can I fold it into this one-liner?

class MyClass
{
private:
  friend static void Callback(void* thisptr); //Declare AND Define as friend
}

Is there another way to fold it all into a single line?

Answer

Please don't downvote, this stems from my lack of knowledge about C++ static member functions. The answer is that they don't need to be friend, they already can access private members. So my question was somewhat invalid.


Solution

  • Actually, no need to use friend if it is static is more accurate. A static member function has access to the internals of the class just like a normal member function. The only difference is it doesn't have a this pointer.

    void MyClass::Callback(void* thisptr) {
        MyClass* p = static_cast<MyClass*>(thisptr);
        p->public_func(); // legal
        p->private_func(); // legal
        p->private_int_var = 0; // legal
    }