By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,260 Members | 1,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,260 IT Pros & Developers. It's quick & easy.

callbacks using function pointers

P: n/a
Hi,

I am trying to implement a callback routine using function pointers.
Basically, I am trying to avoid tying my callback invoking member to a
particular class.

Let me explain my problem with an example. The code snippet below
should help in explaining my problem better.

class A
{
public:
A();
~A();
void func();
private:
int i;
};
A::A()
{
cerr<<" In the constructor of A"<<endl;
i= 100;
}

A::~A()
{

}

void A::func()
{
cout<<"Value of the attribute is "<<i<<endl;
}

class B
{
public:

template <class T>
void callAFunction(void (T::*ptr)());

};

template <class T>
void B::callAFunction(void (T::*ptr)())
{
T *obj = new T;
obj->*ptr();
}

int main()
{
B Bobj;
Bobj.callAFunction(&A::func);

return 0;
}

The callAFunction of class B is expected to call the function whose
pointer (function pointer) is passed to it as an argument, but the
defintion of the function should not be tied to Class A specific
function pointer. For some reason, the compiler cribs at the statement
"obj->*ptr();"

Can anybody point out the error in this code snippet?

Nov 8 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
dr*********@gmail.com wrote:
[..]
template <class T>
void B::callAFunction(void (T::*ptr)())
{
T *obj = new T;
obj->*ptr();
(obj->*ptr)();
} [..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 8 '06 #2

P: n/a

Victor Bazarov wrote in message ...
>dr*********@gmail.com wrote:
>[..]
template <class T>
void B::callAFunction(void (T::*ptr)()){
T *obj = new T;
obj->*ptr();

(obj->*ptr)();
What do you think about adding:

delete obj;
>
>} [..]

V
--
Bob R
POVrookie
Nov 8 '06 #3

P: n/a
BobR wrote:
Victor Bazarov wrote in message ...
>dr*********@gmail.com wrote:
>>[..]
template <class T>
void B::callAFunction(void (T::*ptr)()){
T *obj = new T;
obj->*ptr();

(obj->*ptr)();

What do you think about adding:

delete obj;
Without knowing what the member function does, I would
probably say that it won't hurt, perhaps, most likely.

Of course, if it's all the same, and the function behind
the 'ptr' does not try to retain the pointer to this object,
it might actually be easier to do

(T().*ptr)();

then, instead of those two lines.
>
>>
>>} [..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 9 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.