Skip to main content
gamedev.net
🔒 Locked

Member function pointers

Started by neoztar 3 replies 400+ views
Original Post
neoztar
neoztar

class a {};
class c {};
class b: public c, public a {
  int func(int, int);
};

typedef long (a::*funcptr)(long, long);

void f(a *obj, funcptr ptr) {
  a->*ptr(1, 2);
}

void main() {
  b myobj;
  f(&myobj, &b::func); // Error
}

 
It gives me the error: cannot convert parameter 2 from ''long (__thiscall b::*)(long,long)'' to long (__thiscall a::*)(long,long)''
// Website // Google // GameDev // NeHe // MSDN // OpenGL Extensions //
civguy
civguy
Isn''t it pretty obvious why it doesn''t work? What if someone did this:

  
int main() {
b myobj;
a myotherobj;
f(&myotherobj, &b::func);
}

Now what would happen inside f? A function that''s not part of ''a'' gets executed through an object of type ''a''. Uh, oh.
cgoat
cgoat
What you might want is:


  
class a
{
public:
virtual long func(long, long) = 0;
};

class c
{
};

class b: public c, public a
{
public:
long func(long n1, long n2);
};

typedef long (a::*funcptr)(long, long);

void f(a *obj, funcptr ptr)
{
(obj->*ptr)(1, 2);
}

void main()
{
b myobj;

f(&myobj, &a::func); // Error

}


That will end up calling B''s function, or the defined function of anything derived from A.
thehurricane
thehurricane
This might help:

http://www.parashift.com/c++-faq-lite/pointers-to-members.html

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.