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

Recommended Posts

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 on other sites
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 on other sites
Something like this will work:

// In one fileclass 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 fileclass B{...};

Share on other sites
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 on other sites
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 on other sites
thanks for the heads up. I'll know when I see it now.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628400
• Total Posts
2982450

• 9
• 10
• 9
• 19
• 24