Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 260
unixman83 Avatar asked Dec 31 '11 01:12

unixman83


People also ask

What is the syntax of friend function class?

Syntax of friend functions:class className{ // Other Declarations friend returnType functionName(arg list); }; As we can see above, the friend function should be declared inside the class whose private and protected members are to be accessed.

What is the syntax of static member function?

Static member functions are called using the class name. Syntax- class_name::function_name( )

What is the syntax of static data member?

The static data member is always initialized to zero when the first class object is created. static data_type data_member_name; In the above syntax, static keyword is used. The data_type is the C++ data type such as int, float etc.


1 Answers

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
}
like image 137
jmucchiello Avatar answered Sep 30 '22 15:09

jmucchiello