fork download
  1. #include <iostream>
  2. struct A
  3. {
  4. virtual void print (void) { std::cout << "A called." << std::endl; }
  5. size_t x;
  6. };
  7.  
  8. struct B : A
  9. {
  10. void print (void) { std::cout << "B called." << std::endl; }
  11. };
  12. // "Real" memory layout of A
  13. struct Real_A
  14. {
  15. void * vtable;
  16. size_t x_value;
  17. };
  18. // "Real" memory layout of B
  19. struct Real_B : Real_A
  20. {
  21. size_t y_value;
  22. };
  23. // "Pseudo virtual table structure for classes with 1 virtual function"
  24. struct VT
  25. {
  26. void * func_addr;
  27. };
  28.  
  29. int main (void)
  30. {
  31. A * pa = new A;
  32. pa->x = 15;
  33. B * pb = new B;
  34. pb->x = 20;
  35. A * pa_b = new B;
  36. pa_b->x = 25;
  37. // reinterpret addrress of A and B objects as Real_A and Real_B
  38. Real_A& ra(*(Real_A*)pa);
  39. Real_B& rb(*(Real_B*)pb);
  40. // reinterpret addrress of B object through pointer to A as Real_B
  41. Real_B& rb_a(*(Real_B*)pa_b);
  42. // Print x_values to know whether we meet the class layout
  43. std::cout << "Value of ra.x_value = " << ra.x_value << std::endl;
  44. std::cout << "Value of rb.x_value = " << rb.x_value << std::endl;
  45. std::cout << "Value of rb.x_value = " << rb_a.x_value << std::endl;
  46. // Print vtable addresses
  47. std::cout << "VT of A through A*: " << ra.vtable << std::endl;
  48. std::cout << "VT of B through B*: " << rb.vtable << std::endl;
  49. std::cout << "VT of B through A*: " << rb_a.vtable << std::endl;
  50. // Reinterpret memory pointed to by the vtable address as VT objects
  51. VT& va(*(VT*)ra.vtable);
  52. VT& vb(*(VT*)rb.vtable);
  53. VT& vb_a(*(VT*)rb_a.vtable);
  54. // Print addresses of functions in the vtable
  55. std::cout << "FA of A through A*: " << va.func_addr << std::endl;
  56. std::cout << "FA of B through B*: " << vb.func_addr << std::endl;
  57. std::cout << "FA of B through A*: " << vb_a.func_addr << std::endl;
  58.  
  59. delete pa;
  60. delete pb;
  61. delete pa_b;
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Value of ra.x_value = 15
Value of rb.x_value = 20
Value of rb.x_value = 25
VT of A through A*: 0x8048f38
VT of B through B*: 0x8048f48
VT of B through A*: 0x8048f48
FA of A through A*: 0x8048d40
FA of B through B*: 0x8048cc0
FA of B through A*: 0x8048cc0