127f959d096b9e74cc32483389f5767cb4af539a
[svn/Cll1h/.git] / demos / objects / objects-wiki.c
1 #include "cll1.h"
2
3 /* This is C<<1 rewrite of object polymorphism from
4 http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming */
5
6 def_type(Animal);
7
8 def_mem(Actions)
9 {
10 void method(init) (Animal self, str name);
11 str method(talk) (Animal self);
12 };
13
14 def_obj(Animal)
15 {
16 interface(Actions);
17 char *name;
18 };
19
20 Animal construct(Animal) (Animal self, str name)
21 {
22 self->name = name;
23 return self;
24 }
25
26 str cat_talk(Animal self)
27 {
28 return "Meow!";
29 }
30
31 str dog_talk(Animal self)
32 {
33 return "Arf! Arf!";
34 }
35
36 Actions cat_actions(void)
37 {
38 Actions this=get_mem(Actions);
39 this->talk = cat_talk;
40 return this;
41 }
42
43 Actions dog_actions(void)
44 {
45 Actions this=get_mem(Actions);
46 this->talk = dog_talk;
47 return this;
48 }
49
50 program
51 {
52 int i;
53 Animal animal[3];
54 Actions cat = cat_actions();
55 Actions dog = dog_actions();
56
57 animal[0] = get_obj(Animal, cat, "Missy");
58 animal[1] = get_obj(Animal, cat, "Mr. Bojangles");
59 animal[2] = get_obj(Animal, dog, "Lassie");
60
61 for_range(i, 0, 2)
62 {
63 printf("%s: %s\n", animal[i]->name, _(talk, animal[i]));
64 }
65 }
This page took 0.296725 seconds and 3 git commands to generate.