Syntax for declaring function pointers in C ++

Published on April 10, 2010

Syntax for declaring function pointers in C ++

    When I just started using C ++, all the time I forgot the syntax for defining function pointers and especially member function pointers.

    Later I learned about one small lifehack that helped me get rid of the idea of ​​keeping the syntax for defining pointers to functions in my head. True, a little later, this whole thing somehow settled in my head and it even became obvious.

    The other day I showed this lifehack to one programmer and decided to share it here.

    To avoid long explanations, I will give an example:
    struct test
        virtual int foo (const test &) const
            return 0;
        virtual ~ test ()

    Suppose further by code we need to declare a pointer to test :: foo.
    In order to find out how it should be declared, we will write the following: and try to compile (for example, I will use the compiler from Microsoft, although I checked it with gcc and Comeau Online Compiller). We get the following error:
    char c = &test::foo;

    error C2440: 'initializing': cannot convert from 'int (__thiscall test :: *) (const test &) const' to 'char'

    It is from this error that we take the syntax for declaring a pointer to a given member (explicit indication of the type of the __thiscall call — throw it out):
    int ( test::* )(const test &) const

    Now add a variable and initialization:
    int ( test::* func )(const test &) const = &test::foo;