1

I defined

int(*Functions[3])();

int select(){
cout<<"SELECT!";
getchar();
}

Now i want to assign a function to 'Functions', and when i do like this:

Functions[0]=select;
Functions[0];

It works, but i want to assign function 'select' from my own object

class worker{
HERE DEFINED FUNCTION
}

worker object1;
Functions[0]=object1.select;

It doesn't work. "use '&' to create a pointer to member", " '=':cannot convert from 'int(_thiscall worker::)(void)' to 'int(_cdecl)(void)'"

I don't know a differences between using

select();
object1.select();
3
  • A pointer to non-member function cannot be used for it. Commented Mar 18, 2018 at 23:34
  • Why not? Can you explain? Commented Mar 18, 2018 at 23:36
  • can you use a pointer to int to point to a string? Commented Mar 18, 2018 at 23:43

1 Answer 1

1

A pointer to member function cannot be used for a non-member function and vice-versa. If you want then create another one for a member function in your example.

class Foo{
    public:
        void func(){
            cout << "Foo::func()" << endl;
        }
};

void func2(){
    cout << "func2()" << endl;
}


int main(){

    void(*pFunc[3])();
    pFunc[0] = func2;

    void(Foo::*pFunc2[3])();
    pFunc2[0] = &Foo::func;

    Foo theFoo; // You need an object to call it
    (theFoo.*(pFunc2[0]))(); // calling the member function

    return 0;
}

In addition as @Serge's useful comment:

pointer to a member function requires knowledge of a type of the encapsulating object and an instance of an object at the time it is used. Therefore it is not a simple pointer which you can use for static function only (including static function defined within a class).

Sign up to request clarification or add additional context in comments.

8 Comments

pointer to a member function requires knowledge of a type of the encapsulating object and an instance of an object at the time it is used. Therefore it is not a simple pointer. The simple pointer you can use for static function only (including static function defined within a class). The latter might be just an address of the function in the memory.
It works, but one more question, how to call this function?
@Serge: Thank you for your useful comment.
void print( void(Foo::*pFunc[])(), int size ){ Foo f; for(int i(0); i != size; ++i) (f.*pFunc[i])(); }
you can also pass the object f to function not just declaring it inside the function.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.