Reputation: 12621
I tried to understand how call back works...In the below program passing the (void*)&obj
and receiving it in (void* pt2Object)
is confusing me... *pt2Object
will hold the value and not the address of some variable but here the reference is paased to it..
I could not understand how the ClassA::Wrapper_To_Call_Display
func is passed and get accepted in void (*pt2Function)(void* pt2Object,char* text))
...
Please help me to understand about it..
//---Program To use Function Pointers As A CallBack---
#include "stdafx.h"
#include <iostream>
using namespace std;
class ClassA
{
public:
void Display(const char* text)
{
cout<<text<<endl;
}
static void Wrapper_To_Call_Display(void *pt2Object,char* text);
};
void ClassA::Wrapper_To_Call_Display(void *pt2Object,char* text)
{
ClassA* myself = (ClassA*)pt2Object;
myself->Display("string");
cout<<text<<endl;
}
void DoIt(void* pt2Object, void(*pt2Function)(void* pt2Object, char* text)) {
pt2Function(pt2Object, "Hi I am Calling back using an argument!!");
}
void Callback_Using_Argument() {
ClassA obj;
DoIt((void*)&obj,ClassA::Wrapper_To_Call_Display);
}
int main() {
Callback_Using_Argument();
return 0;
}
string
Hi I am Calling back using an argument!!
Press any key to continue . . .
Upvotes: 1
Views: 223
Reputation: 20272
DoIt((void*)&obj,ClassA::Wrapper_To_Call_Display);
The &obj
is not a reference. &
returns the address of the obj
which is an instance of the ClassA
class.
The next parameter (ClassA::Wrapper_To_Call_Display
) is the address of the function (note that it comes without the ()
that are required for a function call).
*pt2Object will hold the value and not the address of some variable
*pt2Object
is a variable which holds a value. The value is an address of some other variable (that's a pointer).
The whole void*
and casting is a mess and that's not the way it should be done in C++, use casting operators instead.
Upvotes: 1