• Advertisement

Archived

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

ptr to nonstatic memberfunction

This topic is 6249 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi! How to declare a pointer to a class'' member function ? class Dummy { /*...*/ void fnc(); /*...*/ }; // ... Dummy dmy; typedef void (Memberfunction) (void); Memberfunction* pf = dmy.fnc(); pf(); // should call dmy.fnc(); this code results in a compiler error. even if i use a reinterpret_cast there''s an error. How can i declare a pointer to a memberfunction ?? thx for help Teneniel

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
What was the compiler error? I could be mistaken but I think your function pointer declaration looks incorrect. The actual compiler error would help.

Zooraider

Share this post


Link to post
Share on other sites
Jo. right.
i''ve written the following:
class Dummy
{
/*...*/
long fnc (void* ptr);
};

Dummy dmy;

typedef void (Memberfunction) (void);

Memberfunction* pf = dmy.fnc;

pf(); // should call dmy.fnc();

error C2440: ''initializing'' : '''' cannot convert to ''void (__cdecl *)(void)''

so what typedef do i have to use ?

thx
Teneniel

Share this post


Link to post
Share on other sites
Declare a function pointer like this:

ret-type (*func_ptr_name)(parm_list);

And however you want the return type / parameters.

Just make sure you put the *func_ptr_name in brackets, or C''s precedence rules will think your trying to return a pointer to something.

Then just assign it like:

func_ptr_name = some_func;

-Mezz

Share this post


Link to post
Share on other sites
You can''t call a pointer to a member function the same as if it were a normal function.
The compiler internally calls the classes member functions like this
function(class, real parameters)
It cannot be called without the class. However you can do something like this

class Dummy
{
/*..*/
void fnc() { }
};

Dummy dmy;

typedef void (Dummy::*Memberfunction) (void);

Memberfunction pf = dmy.fnc;

(dmy.*pf)(); // should call dmy.fnc();

Share this post


Link to post
Share on other sites
thx mezz, but i''m rying to declare a pointer to a class'' memberfunction.

Assume there''s a class A with the memberfunction void A::someFnc(void);
so i could write:
A a;
a.someFnc();

but what do i have to do if i want to do the following:

typedef void (*MEMBERFNC_PTR) (void);

A a;
MEMBERFNC_PTR ptr = a.someFnc();
// that doesn''t work because the call nees an object..

how can i tell c++ that ptr points to a.someFnc() ???

thx
Teneniel

Share this post


Link to post
Share on other sites

  • Advertisement