Skip to content

Instantly share code, notes, and snippets.

@brokenpylons
Last active April 24, 2019 10:40
Show Gist options
  • Save brokenpylons/22ce721ba9ecc192e7b35d70e4fcbab6 to your computer and use it in GitHub Desktop.
Save brokenpylons/22ce721ba9ecc192e7b35d70e4fcbab6 to your computer and use it in GitHub Desktop.
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
#include <stdio.h>
// base declaration
struct vtable {
int (*bar)(void *);
int (*baz)(void *);
void (*destructor)(void *);
};
struct base {
struct vtable *vpointer;
int x;
int y;
};
void base_constructor(struct base *, int, int);
int base_foo(struct base *);
int base_bar(struct base *);
void base_destructor(struct base *);
extern int base_g;
int base_qux();
// base definition
struct vtable base_vtable = {
.bar = &base_bar,
.baz = 0,
.destructor = &base_destructor
};
void base_constructor(struct base *this, int x, int y)
{
this->vpointer = &base_vtable;
this->x = x;
this->y = y;
}
int base_foo(struct base *this)
{
return this->x;
}
int base_bar(struct base *this)
{
return this->x + this->y;
}
void base_destructor(struct base *this)
{}
int base_g = 0;
int base_qux()
{
return base_g;
}
// derived declaration
struct derived {
struct vtable *vpointer;
int x;
int y;
int z;
};
void derived_constructor(struct derived *, int, int, int);
int derived_bar(struct derived *);
int derived_baz(struct derived *);
void derived_destructor(struct derived *);
// derived definition
struct vtable derived_vtable = {
.bar = &derived_bar,
.baz = &derived_baz,
.destructor = &derived_destructor
};
void derived_constructor(struct derived *this, int x, int y, int z)
{
base_constructor(this, x, y);
this->vpointer = &derived_vtable;
this->z = z;
}
int derived_bar(struct derived *this)
{
return base_bar(this) + this->z;
}
int derived_baz(struct derived *this)
{
return this->z;
}
void derived_destructor(struct derived *this)
{
base_destructor(this);
}
int main()
{
//struct base b;
//base_constructor(&b, 1, 2);
struct derived d;
derived_constructor(&d, 3, 4, 5);
struct base *p = &d;
printf("%i %i %i %i\n", base_foo(p), p->vpointer->bar(p), p->vpointer->baz(p), base_qux());
p->vpointer->destructor(p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment