Function Pointers to Class Functions

Started by
2 comments, last by Prozak 22 years, 3 months ago
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,

[Hugo Ferreira][Positronic Dreams][]
"Research is what I''m doing when I don''t know what I''m doing."
- Wernher Von Braun (1912-1977)

Advertisement
This question has been asked and answered many times before... hint hint...
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:

  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).
-------------------------
method pointers. Look them up (they''re even in the C++ FAQ Lite at parashift.com).

[ GDNet Start Here | GDNet FAQ | MS RTFM | STL | Google ]
Thanks to Kylotan for the idea!

This topic is closed to new replies.

Advertisement