Sign in to follow this  
KumGame

Function Pointers

Recommended Posts

Hi all.. I want some help on array of function pointers in C++. I have a class consisting of few functions.. class A { public : void f1(); void f2(); ..... } In my main() I have something like, main() { void (A::*fptr[2])(); fptr[0] = &A::f1(); fptr[1] = &A::f2(); fptr[0](); // doesn't work } Now, how can I invoke those functions f1() & f2() ? I have tried placing the array of function pointers within the class but no result.

Share this post


Link to post
Share on other sites
A pointer to a (non-static; static member functions are treated just like free functions for the purpose of this discussion) member function is NOT the same kind of thing as an ordinary pointer to a function (or a pointer to anything else for that matter). It represents the abstract concept of "the ability of objects of class A to do f1". But in order to make use of that, you have to have an object of class A, yeah?

To do this, we need (a) an A object, as noted, and (b) some rather funky syntax: the '.*' operator.


A a;
(a.*(fptr[0]))(); // should work


Basically, this is like dereferencing the pointer to get the concept "f1 function of A objects", which is then a valid value to use for member-selecting out of 'a'. The result of that is "bound member function f1 of A object a", which can then be invoked using ().

More here.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by KumGame

I was not aware of '.*' ...


then you might want to read your C/C++ tutorial again, the "." accesses struct/class members, while the "*" dereferences a pointer, thus ".*" dereferences a struct/class pointer. Pretty straightforward in itself and not at all funky syntax.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this