Skip to content
Snippets Groups Projects
Select Git revision
  • 0ba264323975d1dc4dd71499afc9d06ee4ce3d5e
  • master default
2 results

objects-11.c

Blame
  • Forked from Peter Gerwinski / hp
    328 commits behind the upstream repository.
    objects-11.c 1.25 KiB
    #include <stdio.h>
    #include <stdlib.h>
    
    #define T_BASE    0
    #define T_INTEGER 1
    #define T_STRING  2
    
    union t_object;
    
    typedef struct
    {
      int type;
      void (* print) (union t_object *this);
    } t_base;
    
    typedef struct
    {
      int type;
      void (* print) (union t_object *this);
      int content;
    } t_integer;
    
    typedef struct
    {
      int type;
      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.type = 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.type = 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;
    }