Archived

This topic is now archived and is closed to further replies.

Prozak

Function Pointers to Class Functions

Recommended Posts

Prozak    898
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)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
This question has been asked and answered many times before... hint hint...

Share this post


Link to post
Share on other sites
RabidOcelot    122
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).
-------------------------

Share this post


Link to post
Share on other sites