SHARE
TWEET

Example VTable

JoshDreamland Mar 28th, 2016 21 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct enigma_vtable;
  2.  
  3. struct object_locals {
  4.   double x, y;
  5.  
  6.   virtual enigma_vtable *get_vtable() = 0;
  7. };
  8.  
  9. struct enigma_vtable {
  10.   double object_locals::* x, object_locals::* y;
  11.   int object_locals::* one;
  12.   int object_locals::* two;
  13. };
  14.  
  15. struct object0 : object_locals {
  16.   double foo, bar, baz, qux;
  17.   int one;
  18.   double the, quick, brown, fox;
  19.   int two;
  20.  
  21.   static enigma_vtable vtable;
  22.   enigma_vtable *get_vtable() override { return &vtable; };
  23. };
  24. enigma_vtable object0::vtable = {
  25.   &object0::x,
  26.   &object0::y,
  27.   (int object_locals::*) &object0::one,
  28.   (int object_locals::*) &object0::two
  29. };
  30.  
  31. struct object1 : object_locals {
  32.   double foo;
  33.   int one;
  34.   double bar, baz;
  35.   int two;
  36.  
  37.   static enigma_vtable vtable;
  38.   enigma_vtable *get_vtable() override { return &vtable; };
  39. };
  40. enigma_vtable object1::vtable = {
  41.   &object1::x,
  42.   &object1::y,
  43.   (int object_locals::*) &object1::one,
  44.   (int object_locals::*) &object1::two
  45. };
  46.  
  47. struct instance_t {
  48.   object_locals *ref;
  49.   enigma_vtable *vtable;
  50.  
  51.   instance_t(object_locals *direct_ref):
  52.       ref(direct_ref), vtable(ref->get_vtable()) {}
  53.  
  54.   enigma_vtable* operator->() { return vtable; }
  55. };
  56.  
  57. #include <iostream>
  58. using namespace std;
  59.  
  60. int main() {
  61.   object0 inst0;
  62.   object1 inst1;
  63.  
  64.   inst0.x = 1337;
  65.   inst0.y = 1338;
  66.   inst0.one = 1339;
  67.   inst0.two = 13310;
  68.  
  69.   inst1.x = 512;
  70.   inst1.y = 1024;
  71.   inst1.one = 2048;
  72.   inst1.two = 4096;
  73.  
  74.   instance_t inst = &inst0;
  75.  
  76.   cout << inst.ref->*inst->x << endl;
  77.   cout << inst.ref->*inst->y << endl;
  78.   cout << inst.ref->*inst->one << endl;
  79.   cout << inst.ref->*inst->two << endl;
  80.  
  81.   inst = &inst1;
  82.  
  83.   cout << inst.ref->*inst->x << endl;
  84.   cout << inst.ref->*inst->y << endl;
  85.   cout << inst.ref->*inst->one << endl;
  86.   cout << inst.ref->*inst->two << endl;
  87. }
RAW Paste Data
Top