3

I was trying to call a function with a function pointer where the function pointer is a class member.

I simplifed the code to only showcase the problem but the foo() function in the oiginal code is already writen so I cannot change it.

(In my actual code, foo is from GLFW (glfwSetKeyCallback) and A is an input handler class.)

The code is:

    #include <iostream>

    // this four line can not be changed
    typedef void(*fptr)(int);
    void foo(fptr f) {
        f(0);
    }

    void testOutA(int i) {
    }

    class A {
    public:
        void testInA(int i) {
        }
    };

    int main()
    {
        foo(testOutA); // works fine as it should be

        A * a = new A();

        foo(a->testInA); // ERROR

        return 0;
    }

The compilation error message is:

ERROR: error C3867: 'A::testInA': non-standard syntax; use '&' to create a pointer to member

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Sekkmer
  • 103
  • 1
  • 12

1 Answers1

4

The type of the expression a->testInA is a pointer to a non-static member function.

It does not have the same type as fptr, so the compiler emits an error, albeit a cryptic one.

Compilation would pass if testInA were static.

See C++ function pointer (class member) to non-static member function for more details.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483