Sign in to follow this  
wease

Can function pointers point to functions defined outside their native class?

Recommended Posts

wease    148
Hello, I have a class that contains some function pointers. I would like to define the actual functions that these function pointers point to in a different file (ie, not in the same class as the one containing the function pointers). Does anyone know if this is possible?

Share this post


Link to post
Share on other sites
Fruny    1658
a) Pointers to non-member functions and pointers to (non-static) member functions are two very different kind of creatures. Make sure you know which ones you want, they are not interchangeable.

b) Yes, you can point to functions that are defined somewhere else, so long as your function pointer has the correct type.

Share this post


Link to post
Share on other sites
Aprosenf    372
Something like this will work:

// In one file
class B; // This merely tells the compiler that a class named B exists somewhere else

class A
{
int (B::*funcPtr)(void); // This is a pointer named funcPtr that points to a method of the B class that takes no arguments and returns an int

public:
void setFuncPtr(int (B::*ptr)(void)) { funcPtr = ptr; }
...
};

// In another file
class B
{
...
};

Share this post


Link to post
Share on other sites
wease    148
thank you so much for your help. Every time I post here I'm always shocked at how quick and helpful the posts are.

Share this post


Link to post
Share on other sites
rKallmeyer    396
You have to be very careful doing that in MSVC++. If you use multiple or virtual inheritance in class B, then you will be staring at obscure compiler errors for hours.

Pointers to member functions are different sizes in MSVC++ (and some other compilers) based upon what kind of inheritance their class uses.

The problem is that the compiler doesn't know what inheritance class B uses so it has to guess when you prototype it. If it guesses wrong, you will run into problems.

You have two options:

1) Use the microsoft specific inheritance keywords.

or

2) Use the compiler option /vmg which tells it to use a general case member function pointer type.

I prefer the later because it keeps your code portable and clear. The downside is that each member-function pointer takes up 16 bytes, which might be an issue for embedded systems.

Check out this page for a much better description of the problem then I have given.

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