ptr to nonstatic memberfunction

Started by
5 comments, last by teneniel 23 years, 3 months ago
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
Advertisement
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
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
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
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();
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
damn you''re good!!
Thanks LeeIsMe!!

Teneniel








This topic is closed to new replies.

Advertisement