#include <iostream>
using namespace std;
typedef void (*pFun)(void);
class A
{
private:
int a;
int b;
virtual void outPrint()
{
cout << b << endl;
}
public:
A()
{
a = 3;
b = 4;
}
};
int main()
{
A obj;
cout << *((int*)(&obj)+1) << endl;
pFun pFunc;
pFunc = (pFun)*((int*)*(int*)(&obj));
pFunc();
system("pause");
return 0;
}
when i call pFunc(), the result i think should be 4,but actually it’s a random number.
and i debug the program, finding that pFunc points to the outPrint function. i don’t know why,plz help me
Seems that you assume that the address of the object
objcan be interpreted as an address of a function of the type you defined.It cannot.
I’m not entirely sure why would you have such an assumption to begin with. You’re probably assuming things about the internal implementation of the dynamic dispatch. But do take a note:
A::outPrintthat you expect to be called, accepts 1 parameter (this, that is not explicitly defined), whereas your typedef assumes no parameters. So even if the address casting works fine and the address you get is that of the member function (which is a stretch to begin with), your call is incorrect.If you change the typedef to:
and the call to
That might work. Yet, the behavior per spec is undefined, to the best of my understanding.