callbacks using function pointers

D

drsantosh82

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?
 
V

Victor Bazarov

BobR said:
Victor Bazarov wrote in message ...
[..]
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,591
Members
45,100
Latest member
MelodeeFaj
Top