locked
Function Typedef's RRS feed

  • Question

  • typedef int (*myfunction)(int);

    class MyClass{

    MyClass();

    myfunction func;
    };


    int MyClass::func(int x)
    {
    return x;
    }


    Take a look at the above code.  The compiler keeps telling me func is not a member of MyClass.

    I'm confused.

    Saturday, January 2, 2010 6:55 AM

Answers

  • Do like this

    #include <assert.h>

    typedef int (*myfunction)(int);

    class MyClass
    {
    public:
        MyClass(myfunction f):func(f){}
        myfunction func;
    };


    int f(int x)
    {
        return x;
    }

    int main()
    {
        MyClass myClass(f);
        int nTest = myClass.func(10);
        assert(nTest == 10);
        return 0;
    }


    David Wilkinson | Visual C++ MVP
    • Marked as answer by Unhandled Saturday, January 2, 2010 9:59 PM
    Saturday, January 2, 2010 10:05 AM

All replies

  • Do like this

    #include <assert.h>

    typedef int (*myfunction)(int);

    class MyClass
    {
    public:
        MyClass(myfunction f):func(f){}
        myfunction func;
    };


    int f(int x)
    {
        return x;
    }

    int main()
    {
        MyClass myClass(f);
        int nTest = myClass.func(10);
        assert(nTest == 10);
        return 0;
    }


    David Wilkinson | Visual C++ MVP
    • Marked as answer by Unhandled Saturday, January 2, 2010 9:59 PM
    Saturday, January 2, 2010 10:05 AM
  • Thanks.

    When I do this:

    typedef int (myfunction)(int);

    class MyClass{

    MyClass();

    myfunction func;
    };


    int MyClass::func(int x)
    {
    return x;
    }



    It works!

    All I did was remove the * from the typedef.  I think I accidentally defined a pointer to a function and not a function pointer.

    I understand your solution; basically you are using a global function instead and passing the address into the class.

    Your answer worked but I'm wondering if I needed to include the * in the typedef in the first place.  I always thought you needed to include it to tell the compiler you are typdefing a pointer, but I guess the notation, (),  implies a pointer. 
    Saturday, January 2, 2010 9:59 PM
  • Thanks.

    When I do this:

    typedef int (myfunction)(int);

    class MyClass{

    MyClass();

    myfunction func;
    };


    int MyClass::func(int x)
    {
    return x;
    }


    Ah yes, anew thing learned.

    Actually you do not need the parentheses. You can just do

    typedef int myfunction(int);

    This is a different typedef declaration from your original pointer to function typedef.

    Even inside the MyClass definition, the declaration

    myfunction func;

    is equivalent to

    int func(int);

    which is why your new code works.

    My thanks to Visual C++ MVP Igor Tandetnik for a private discussion on this topic.







    David Wilkinson | Visual C++ MVP
    Sunday, January 3, 2010 5:50 PM