Skip to content

Instantly share code, notes, and snippets.

@michahoiting
Created April 12, 2016 13:23
Show Gist options
  • Save michahoiting/1aec1c95881881add9a20e9839c35cec to your computer and use it in GitHub Desktop.
Save michahoiting/1aec1c95881881add9a20e9839c35cec to your computer and use it in GitHub Desktop.
vtable example in C
#include <stdio.h>
/* class definitions */
typedef struct Base
{
void (**vtable)();
int _x;
} Base;
typedef struct Child
{
void (**vtable)();
/* begin base class slice */
int _x;
/* end base class slice */
int _y;
} Child;
/* class method implementations */
void Base_ToString(Base const* obj) { printf("Base: (%d)\n", obj->_x); }
void Child_ToString(Child const* obj) { printf("Base: (%d,%d)\n", obj->_x, obj->_y); }
/* soley method pointer */
void (*fn_ptr)();
/* vtable implementation */
enum { Call_ToString };
void (*Base_Vtable[])() = { Base_ToString };
void (*Child_Vtable[])() = { [Call_ToString] = Child_ToString }; /* gcc designated inits */
/* virtual method implementation */
void ToString(Base const* obj)
{
obj->vtable[Call_ToString](obj);
}
int main()
{
/* pick the vtable for objects at compile time */
Base base = {Base_Vtable, 123};
Child child = {Child_Vtable, 456, 789};
Child object = {NULL, 12, 14};
Base* a = &base;
Base* b = (Base*)&child;
Base* c = (Base*)&object;
/* call the virtual methods */
ToString(a);
ToString(b);
fn_ptr = Child_ToString;
fn_ptr(c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment