Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Sep 20, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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()
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date