Skip to content

Instantly share code, notes, and snippets.

@lighth7015
Forked from michahoiting/c-vtable.c
Created April 27, 2020 12:40
Show Gist options
  • Save lighth7015/a0953a93a9f1ac8934229766c91ac19a to your computer and use it in GitHub Desktop.
Save lighth7015/a0953a93a9f1ac8934229766c91ac19a 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