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