Select Git revision
objects-12.c
objects-12.c 1.10 KiB
#include <stdio.h>
#include <stdlib.h>
union t_object;
typedef struct
{
void (* print) (union t_object *this);
} t_base;
typedef struct
{
void (* print) (union t_object *this);
int content;
} t_integer;
typedef struct
{
void (* print) (union t_object *this);
char *content;
} t_string;
typedef union t_object
{
t_base base;
t_integer integer;
t_string string;
} t_object;
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_object *new_integer (int i)
{
t_object *p = malloc (sizeof (t_integer));
p->integer.print = print_integer;
p->integer.content = i;
return p;
}
t_object *new_string (char *s)
{
t_object *p = malloc (sizeof (t_string));
p->string.print = print_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.print (object[i]);
return 0;
}