Search code examples
c++function-pointers

Function pointer issue: How to provide pointer from non member function to member function


i need to do something like this ..., in a project of mine.

class Alpha{
    
public:
    Alpha(void* p(int, int) = nullptr);
        
    void* calculatePointer;
    
    void test();
};
    

Alpha::Alpha(void* p(int, int)) : calculatePointer(p){};

Alpha::test(){
        calculatePointer(5, 10);
    }  


  
    
void calculate(int a, int b){
    std::cout << "cum: " << a +b << "\n";  
}
    
    
int main(){
    
    Alpha A = Alpha(&calculate);
    A.test();
    
}

and it results in in these errors:

error: invalid conversion from ‘void* (*)(int, int)’ to ‘void*’ [-fpermissive]
       15 |     : calculatePointer(p),
          |                        ^
          |                        |
          |                        void* (*)(int, int)
error: cannot initialize a member subobject of type 'void *' with an lvalue of type 'void *(*)(int, int)'
     error: expression cannot be used as a function
     In constructor 'Alpha::Alpha(void* (*)(int, int))':
    error: invalid conversion from 'void (*)(int, int)' to 'void* (*)(int, int)' [-fpermissive]
note: initializing argument 1 of 'Alpha::Alpha(void* (*)(int, int))'

this is just a dummy, but that's what i gotta do.
how is it done correctly?


Solution

  • If you're confused about the exact syntax of a function pointer it's probably best to define a type alias.

    If you use using, the "rhs" is <return type> (*)(<parameter types>)

    class Alpha{
        
    public:
        using FunctionPtr = void (*)(int, int);
    
        Alpha(FunctionPtr p = nullptr) : calculatePointer(p) {}
            
        FunctionPtr calculatePointer;
        
        void test()
        {
            if (calculatePointer != nullptr)
            {
                calculatePointer(5, 10);
            }
        }
    };
        
    void calculate(int a, int b){
        std::cout << "sum: " << (a + b) << "\n";  
    }
    

    Btw: the correct syntax without a type alias would be

    Alpha(void (*p)(int, int) = nullptr);
    

    the brackets are necessary, since the compiler treats void *p(int, int) as (void*) p(int, int).