Select Git revision
objects-13.c
Forked from
Peter Gerwinski / hp
341 commits behind the upstream repository.
Peter Gerwinski authored
objects-13.c 1.20 KiB
#include <stdio.h>
#include <stdlib.h>
union t_object;
struct t_vmt;
typedef struct
{
struct t_vmt *vmt;
} t_base;
typedef struct
{
struct t_vmt *vmt;
int content;
} t_integer;
typedef struct
{
struct t_vmt *vmt;
char *content;
} t_string;
typedef union t_object
{
t_base base;
t_integer integer;
t_string string;
} t_object;
typedef struct t_vmt
{
void (* print) (union t_object *this);
} t_vmt;
void print_integer (t_object *this)
{
printf ("Integer: %d\n", this->integer.content);
}
void print_string (t_object *this)
{
printf ("String: \"%s\"\n", this->string.content);
}
t_vmt vmt_integer = { print_integer };
t_vmt vmt_string = { print_string };
t_object *new_integer (int i)
{
t_object *p = malloc (sizeof (t_integer));
p->integer.vmt = &vmt_integer;
p->integer.content = i;
return p;
}
t_object *new_string (char *s)
{
t_object *p = malloc (sizeof (t_string));
p->integer.vmt = &vmt_string;
p->string.content = s;
return p;
}
int main (void)
{
t_object *object[] = { new_integer (42),
new_string ("Hello, world!"),
NULL };
for (int i = 0; object[i]; i++)
object[i]->base.vmt->print (object[i]);
return 0;
}