[Hugo Ferreira][Positronic Dreams][]
"Research is what I''m doing when I don''t know what I''m doing."
- Wernher Von Braun (1912-1977)
Function Pointers to Class Functions
I have a function in a class (CWindow) that looks like this:
void fname(void);
And I have a function pointer in my main code area, that looks like this:
void (*fptr)(void);
why is it that i cannot do:
fptr=cname.fname; ??
All I get is a:
error C2440: ''='' : cannot convert from ''void (__thiscall CWindow::*)(void)''
to ''void (__cdecl *)(void)''
The Compiler does allow me to do this:
void (CWindow::*fptr)(void);
fptr=cname.Show();
But I cannot call functions using that pointer, so, it misses the point.
In short, how do I create a pointer to a function in a class?
Thanx for any input,
As far as I know, you can only take the address of a static member function. I believe the reason (correct me if I''m wrong)is that non static member functions are implicitly passed the this pointer when they are called. Since this is done internally, allowing a non static member function to be called via pointer would remove the function''s ability to reference this.
As for the code you posted:
This actually calls cname.Show() and sets fptr to the value returned. Your compiler shouldn''t let you do this, as void is not a returnable type.
One option is to make your function static, and access it like so:
If making the function static isn''t feasable, you''ll have to find another workaround, like storing a pointer to the object itself.
Game: The Adventure (tm).
-------------------------
As for the code you posted:
fptr=cname.Show();
This actually calls cname.Show() and sets fptr to the value returned. Your compiler shouldn''t let you do this, as void is not a returnable type.
One option is to make your function static, and access it like so:
#include <iostream>class MyClass{ public: static void SayHello (void) {cout << "Hello" << endl;}};int main (void){ MyClass a; void (*pHello) (void); pHello = a.SayHello; pHello (); return 1;}
If making the function static isn''t feasable, you''ll have to find another workaround, like storing a pointer to the object itself.
Game: The Adventure (tm).
-------------------------
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement