b27abb8a |
1 | #include "cll1.h" |
097bac9a |
2 | |
3 | /* This is C<<1 rewrite of object polymorphism from |
47e4883a |
4 | http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming |
5 | |
6 | Of course there are easier ways to do the same thing... :-) |
7 | (G)2008 xChas */ |
b27abb8a |
8 | |
9 | def_mem(Actions) |
097bac9a |
10 | { |
47e4883a |
11 | str method(talk) (anonymous self); |
097bac9a |
12 | }; |
13 | |
47e4883a |
14 | def_mem(Animal) |
097bac9a |
15 | { |
b27abb8a |
16 | interface(Actions); |
17 | char *name; |
18 | }; |
097bac9a |
19 | |
47e4883a |
20 | construct(Animal) (Animal self, str name) |
1a8d78d9 |
21 | { |
22 | self->name = name; |
23 | return self; |
24 | } |
25 | |
47e4883a |
26 | str cat_talk(anonymous self) |
097bac9a |
27 | { |
b27abb8a |
28 | return "Meow!"; |
097bac9a |
29 | } |
30 | |
47e4883a |
31 | str dog_talk(anonymous self) |
097bac9a |
32 | { |
b27abb8a |
33 | return "Arf! Arf!"; |
097bac9a |
34 | } |
35 | |
1a8d78d9 |
36 | Actions cat_actions(void) |
097bac9a |
37 | { |
47e4883a |
38 | Get_mem(this,Actions); |
39 | |
b27abb8a |
40 | this->talk = cat_talk; |
1a8d78d9 |
41 | return this; |
097bac9a |
42 | } |
43 | |
1a8d78d9 |
44 | Actions dog_actions(void) |
097bac9a |
45 | { |
47e4883a |
46 | Get_mem(this,Actions); |
47 | |
b27abb8a |
48 | this->talk = dog_talk; |
1a8d78d9 |
49 | return this; |
097bac9a |
50 | } |
51 | |
52 | program |
53 | { |
54 | int i; |
b27abb8a |
55 | Animal animal[3]; |
56 | Actions cat = cat_actions(); |
57 | Actions dog = dog_actions(); |
097bac9a |
58 | |
47e4883a |
59 | animal[0] = get_obj(Animal,cat,"Missy"); |
60 | animal[1] = get_obj(Animal,cat,"Mr. Bojangles"); |
61 | animal[2] = get_obj(Animal,dog,"Lassie"); |
097bac9a |
62 | |
b27abb8a |
63 | for_range(i, 0, 2) |
64 | { |
47e4883a |
65 | print(animal[i]->name,":",_(talk,animal[i])); |
b27abb8a |
66 | } |
097bac9a |
67 | } |