#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
struct B{
const char * str;
void bar(){cout << str << endl;};
B(){str = "B";}
};
struct D1 : public virtual B{
const char * str;
void bar(){cout << str << endl;}
D1(){
str = "D1";
}
};
struct D2 : public virtual B{
const char * str;
void bar(){cout << str <<endl;};
D2(){
str = "D2";
}
};
struct C : public D1, public D2{
const char * str;
void bar(){cout << str << endl;};
C(){
str = "C";
}
};
void hexDump(void *ptr,size_t size){
printf("%d bytes at %p: ",size,ptr);
unsigned char *p = (unsigned char*) ptr;
for(size_t i =size-1;i!=0;i--){
printf("%02X",p[i]);
}
printf("%02X",p[0]);
printf("\n");
}
template<class T>
void *forceCast(T ptr){
return *((void**)&ptr);
};
int main(){
int i;
int *p = &i;
void(B::*pB)() = &B::bar;
void(D1::*pD1)() = &D1::bar;
void(D2::*pD2)() = &D2::bar;
void(C::*pC)() = &D2::bar;
printf("\nint *p size: %u\n",sizeof(p));
hexDump(&p,sizeof(p));
printf("printf: %p\n",p);
cout << "cout forceCast: "<< forceCast(p) <<endl;
printf("\nint *pB size: %u\n",sizeof(pB));
hexDump(&pB,sizeof(pB));
printf("printf: %p\n",pB);
cout << "cout forceCast: "<< forceCast(pB) <<endl;
printf("\nvoid(D1::*pD1)() size: %u\n",sizeof(pD1));
hexDump(&pD1,sizeof(pD1));
printf("printf: %p\n",pD1);
cout << "cout forceCast: "<< forceCast(pD1) <<endl;
printf("\nvoid(C::*pC)() size: %u\n",sizeof(pC));
hexDump(&pC,sizeof(pC));
printf("printf: %p\n",pC);
cout << "cout forceCast: "<< forceCast(pC) <<endl;
//hexDump(&pvC,sizeof(pvC));
C *c = new C();
(c->*pB)();
(c->*pD1)();
(c->*pC)();
printf("\n\nreplacing pC's content with (void*) pC\n");
void* ptr = forceCast(pC);
memset(&pC,0,sizeof(pC));
memcpy(&pC,&ptr,sizeof(ptr));
printf("\nvoid(C::*pC)() size: %u\n",sizeof(pC));
hexDump(&pC,sizeof(pC));
printf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