Returning a Pointer to a Member Function

Returning a Pointer to a Member Function

Let’s say I have a class foo, with a lot of functions that take no arguments and return SomeType:

SomeType foo::bar()SomeType foo::quux()SomeType foo::quuux()SomeType foo::quuuux()

Now I have a pointer to this type of funct :

SomeType (foo::*pfn)();

Now comes the tough part, I want to return it:

?????? SomeFnct(){   SomeType (foo::*pfn)();   pfn = foo::quux;   return pfn;}

What do I write instead of the ??????

Pointers to members can baffle even experienced C++ programmers. There are, however, some syntactic clues that can be helpful. First, let's look at an example that returns a pointer to an ordinary function:

int (*ipifd(int))(double){/*..*/}

The above code snippet declares a function named ipifd that takes double and returns a pointer to a function that takes int and returns int.

Pointers to member functions are very similar to ordinary pointers to function, except that they have an additional qualified name before the asterisk. Thus, for a class named C, the following declaration:

int (C::*ipmifd(int))(double);

declares a function ipmifd that takes a double and returns a pointer to a member function of class C which takes int and returns int.

Now back to your class. A function that takes no argument and returns a member to function of foo, which in turn takes no arguments and returns int, looks like this:

int (foo::*ipifi())(){/*..*/}

This is cumbersome and error prone. In general, you should avoid using such constructs directly because other programmers will have a really hard time understanding what this declaration means. To improve code readability, I recommend using a tydepef to hide the ugly syntax:

typedef int (foo::*PFN)();

Now, defining a function that returns a PFN is trivial:

PFN func(){/*..*/} 

See also  5 Ways to Improve Customer Experience

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist