C++: Function Pointer assignment cannot convert types



  • I am having issues properly declaring and using function pointers to functions defined inside a class:

    all works fine for use case outside a class, for example:

    typedef bool (*FunctionPointerType1)(int&);
    bool functionImplementation1(int& a) {
        a++;    // Just increments the parameter
    }
    FunctionPointerType1 getFunctionPointer1() {
        return functionImplementation1;
    }
    int main(int argc, char *argv[])
    {
        FunctionPointerType1 imp1 = getFunctionPointer1();
    

    Repeating the same exercise for a function defined inside a class I get to see the issue, why?

    class MainClass {
    private:
        typedef bool (MainClass::*FunctionPointerType)(int&);
        bool functionImplementation(int& a) {
        a++;    // Just increments the parameter
    }
    FunctionPointerType getFunctionPointer() {
        return functionImplementation;
        /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^
            error: cannot convert 'MainClass::functionImplementation' from type 'bool (MainClass::)(int&)' to type 'MainClass::FunctionPointerType {aka bool (MainClass::*)(int&)}'
        */
    }
    public:
    

  • Moderators

    @Alex94102

    I think this should be:

      typedef bool (MainClass::*FunctionPointerType)(int&);


  • Yes thanks, the post did't render the correctly, I re-posted that. That's exactly how it was to start with.


  • Qt Champions 2016

    @Alex94102

    FunctionPointerType getFunctionPointer()
    {
        return &MainClass::functionImplementation;
    }
    

    ?



  • **I want to cry! Thank you soooooo much! I really appreciated your help. **


  • Qt Champions 2016

    smiley


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.