Skip to content

Instantly share code, notes, and snippets.

@drewxa
Last active May 19, 2019 12:51
Show Gist options
  • Save drewxa/55a9d71c0b765a91564cd789a0454787 to your computer and use it in GitHub Desktop.
Save drewxa/55a9d71c0b765a91564cd789a0454787 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
void
base_function (void *const this_obj)
{
std::cout << "b" << std::endl;
}
void
derived_function (void *const this_obj)
{
std::cout << "d" << std::endl;
}
struct base
{
struct VFT
{
void (*virtual_function) (void *const this_obj) = nullptr;
};
VFT *vft;
};
struct derived : public base
{
int r;
};
base::VFT * construct_base_vft ()
{
static base::VFT * vtf = new base::VFT ();
vtf->virtual_function = base_function;
return vtf;
}
base::VFT * construct_derived_vft ()
{
static base::VFT * vtf = new base::VFT ();
vtf->virtual_function = derived_function;
return vtf;
}
base *
construct_base ()
{
base *obj = new base ();
obj->vft = construct_base_vft ();
return obj;
}
derived *
construct_derived ()
{
derived *obj = new derived ();
obj->vft = construct_derived_vft ();
return obj;
}
void one_point(void* base_ptr) {
reinterpret_cast<base*>(base_ptr)->vft->virtual_function(base_ptr);
}
int main ()
{
derived* d = construct_derived();
base* b = construct_base();
one_point(b);
one_point(d);
delete d;
delete b;
delete construct_base_vft();
delete construct_derived_vft();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment