Board index » cppbuilder » method pointers

method pointers


2005-09-20 10:37:04 PM
cppbuilder68
what is the syntax to pass a method pointer from one class to another?
luca
 
 

Re:method pointers

"luca" < XXXX@XXXXX.COM >writes:
Quote
what is the syntax to pass a method pointer from one class to another?
struct A
{
// a member function
double f(int);
};
struct B
{
// another member function, taking a pointer to a member function as
// parameter
void g(double (A::*fp)(int));
};
int main()
{
B b;
// taking the address of a member function and use it as argument
b.g(&A::f);
}
 

Re:method pointers

"luca" < XXXX@XXXXX.COM >wrote in message
Quote
what is the syntax to pass a method pointer from one class to another?
If you are ok to be Borland specific, you can use this method:
typedef void __fastcall (__closure *MyMethodPointer)();
class Test1
{
public:
Test1() { };
void __fastcall MethodToCall()
{
printf( "MethodToCall()\n" );
};
};
class Test2
{
private:
Test1 t;
MyMethodPointer Method;
public:
Test2()
{
Method = t.MethodToCall;
};
void __fastcall CallMethod()
{
Method();
}
};
int main()
{
Test2 t;
t.CallMethod();
return 0;
}
Otherwise (and I hope that I'm giving correct C++, it is tested in bcc,
mcvc and gcc):
class Test1
{
public:
Test1() { };
void MethodToCall()
{
printf( "MethodToCall()\n" );
};
};
typedef void (Test1::*MyMethodPointer)();
class Test2
{
private:
Test1 t;
MyMethodPointer Method;
public:
Test2()
{
Method = &Test1::MethodToCall;
};
void CallMethod()
{
(&t->*Method)();
};
};
int main()
{
Test2 t;
t.CallMethod();
return 0;
}
HTH
Jonathan
 

{smallsort}

Re:method pointers

"luca" < XXXX@XXXXX.COM >writes:
Quote
what is the syntax to pass a method pointer from one class to another?
Here's an example using standard C++. Borland has a nice, nonstandard
way called __closure, but someone else can describe that. (Or you
could even read about it yourself!) <G>
#include <iostream>
class B;
class A
{
public:
typedef void (B::*B_Func)(int);
A(B * ptr) : b_(ptr) { }
void receive(B_Func ptr_b_func, int val);
private:
B * b_;
};
class B
{
public:
void f(int x ) { std::cout << "called f(" << x << ')' << std::endl; }
void g(int x ) { std::cout << "called g(" << x << ')' << std::endl; }
};
// pass val into function pointed-to-by ptr_b_func, called on the
// B member we store:
void A::receive(A::B_Func ptr_b_func, int val)
{
(b_->*ptr_b_func)(val);
}
int main()
{
B b;
A a(&b);
a.receive(&B::f, 123);
a.receive(&B::g, 321);
}
--
Chris (TeamB);
 

Re:method pointers

bcbjournal.com/articles/vol4/0007/Understanding_function_pointers.htm
"luca" < XXXX@XXXXX.COM >wrote in message
Quote
what is the syntax to pass a method pointer from one class to another?

luca