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 | |
96ec74e5 |
9 | def_type(Animal); |
10 | |
b27abb8a |
11 | def_mem(Actions) |
097bac9a |
12 | { |
96ec74e5 |
13 | str method(talk) (Animal self); |
097bac9a |
14 | }; |
15 | |
96ec74e5 |
16 | def_obj(Animal) |
097bac9a |
17 | { |
b27abb8a |
18 | interface(Actions); |
19 | char *name; |
20 | }; |
097bac9a |
21 | |
24cfa6bd |
22 | construct(Animal,Actions) (Animal self, str name) |
1a8d78d9 |
23 | { |
24 | self->name = name; |
25 | return self; |
26 | } |
27 | |
96ec74e5 |
28 | /* implementation of methods */ |
29 | |
30 | str catTalk(Animal self) |
097bac9a |
31 | { |
b27abb8a |
32 | return "Meow!"; |
097bac9a |
33 | } |
34 | |
96ec74e5 |
35 | str dogTalk(Animal self) |
097bac9a |
36 | { |
b27abb8a |
37 | return "Arf! Arf!"; |
097bac9a |
38 | } |
39 | |
96ec74e5 |
40 | /* registration of methods to object interface */ |
41 | |
42 | Actions catActions(void) |
097bac9a |
43 | { |
96ec74e5 |
44 | Get_mem(this, Actions); |
47e4883a |
45 | |
96ec74e5 |
46 | this->talk = catTalk; |
1a8d78d9 |
47 | return this; |
097bac9a |
48 | } |
49 | |
96ec74e5 |
50 | Actions dogActions(void) |
097bac9a |
51 | { |
96ec74e5 |
52 | Get_mem(this, Actions); |
47e4883a |
53 | |
96ec74e5 |
54 | this->talk = dogTalk; |
1a8d78d9 |
55 | return this; |
097bac9a |
56 | } |
57 | |
96ec74e5 |
58 | /* usage of objects inside C<<1 program */ |
59 | |
097bac9a |
60 | program |
61 | { |
62 | int i; |
b27abb8a |
63 | Animal animal[3]; |
96ec74e5 |
64 | Actions cat = catActions(); |
65 | Actions dog = dogActions(); |
097bac9a |
66 | |
96ec74e5 |
67 | animal[0] = get_obj(Animal, cat, "Missy"); |
68 | animal[1] = get_obj(Animal, cat, "Mr. Bojangles"); |
69 | animal[2] = get_obj(Animal, dog, "Lassie"); |
097bac9a |
70 | |
b27abb8a |
71 | for_range(i, 0, 2) |
72 | { |
bd69f0f0 |
73 | print(animal[i]->name, ":", _(talk, animal[i])); |
b27abb8a |
74 | } |
bd69f0f0 |
75 | |
097bac9a |
76 | } |