Skip to content

Instantly share code, notes, and snippets.

@kolosovpetro
Created September 10, 2021 14:48
Show Gist options
  • Select an option

  • Save kolosovpetro/0f5f1cca1023dfbf767feeb178d353f5 to your computer and use it in GitHub Desktop.

Select an option

Save kolosovpetro/0f5f1cca1023dfbf767feeb178d353f5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Base_;
typedef struct Base_VTable_
{
char* (*ToString)(struct Base_*);
} Base_VTable;
Base_VTable Base_VTable_Obj;
typedef struct Base_
{
Base_VTable* vtable;
} Base;
void Base_Init(Base* this)
{
this->vtable = &Base_VTable_Obj;
}
typedef struct Derived_
{
Base base;
int a;
} Derived;
char* Derived_ToString(Derived* this)
{
char buffer[80];
sprintf(buffer, "%d", this->a);
return strdup(buffer);
};
void Derived_Init(Derived* this)
{
Base_Init((Base*)this);
this->a = 42;
((Base*)this)->vtable->ToString = Derived_ToString;
}
int main()
{
Derived d;
Derived_Init(&d);
char* str = ((Base*)&d)->vtable->ToString(&d);
puts(str);
free(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment