Skip to content
Snippets Groups Projects
Select Git revision
  • 4ff440eaac9aee21bd0a6c7f5ce7927ee4cd9b94
  • master default
2 results

objects-13.c

Blame
  • Forked from Peter Gerwinski / hp
    341 commits behind the upstream repository.
    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;
    }