Okay, pfoo will contain the address of the function TheClass::foo right? |
Well the code you posted is not quite C++ and would not compile... but in theory, yes.
That is the same address whether we put
aClass.foo or bClass.foo
So how do fooUsing "know" which class function to call? aClass.foo or bClass.foo? |
That's exactly why you don't do it this way. You pass a pointer to a function, but in order to call the function you still need an object... so you would have to pass something else to fooUsing.
Some says that a pointer to the class itself is passed on to a function. |
This is correct. Non-static member functions have a hidden, implicit 'this' pointer passed to them. That pointer is the pointer to the object they're referencing.
But that means fooUsing will be using a function that takes parameter of type TheClass and not a no parameter |
Yes and no.
Yes because behind the scenes, C++ will pass the this pointer the same way it passes function parameters.
No because you don't pass the object as a pointer, but rather you just have different syntax.
Here's how you would do your example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
Class TheClass
{
public:
void foo() { }
};
void fooUsing(
void (TheClass::*func)(), // the syntax for a pointer to a member function
TheClass& obj ) // the object with which to call the function on
{
(obj.*func)(); // call the function with 'obj' as the object
}
int main()
{
TheClass aClass;
fooUsing( &TheClass::foo, aClass ); // give it the function pointer, and the object
}
|
Of course this is horrendously ugly and hard to remember how to do (I had to look it all up -- I couldn't remember the syntax offhand). Which is just another reason to avoid using function pointers. C++ provides alternatives that are generally much easier to use and a lot safer.