Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to member function for as argument for global function

Tags:

c++

There is such code:

void foo(void (*fun_ptr)()){

}

class B{
public:
    B(){
        foo(some_fun);
    }
    void some_fun(){}
};

Compilation error:

error: argument of type ‘void (B::)()’ does not match ‘void (*)()’

How to point to member function in this case? I cannot change declaration of function foo, only class B!

like image 249
scdmb Avatar asked Oct 02 '26 21:10

scdmb


1 Answers

Declare B::some_fun() as static as there is an implicit this pointer passed as an argument to member functions. Note that making B::some_fun() static prevents access to non-public non-static members of B.

like image 53
hmjd Avatar answered Oct 04 '26 09:10

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!