def_interface() in object demo
[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 Of course there are easier ways to do the same thing... :-)
7 (G)2008 xChas */
8
9 def_interface(Animal,Actions)
10 {
11 str method(talk) (Animal self);
12 };
13
14 def_obj(Animal)
15 {
16 interface(Actions);
17 char *name;
18 };
19
20 construct(Animal,Actions) (Animal self, str name)
21 {
22 self->name = name;
23 return self;
24 }
25
26 /* implementation of methods */
27
28 str catTalk(Animal self)
29 {
30 return "Meow!";
31 }
32
33 str dogTalk(Animal self)
34 {
35 return "Arf! Arf!";
36 }
37
38 /* registration of methods to object interface */
39
40 Actions catActions(void)
41 {
42 Get_mem(this, Actions);
43
44 this->talk = catTalk;
45 return this;
46 }
47
48 Actions dogActions(void)
49 {
50 Get_mem(this, Actions);
51
52 this->talk = dogTalk;
53 return this;
54 }
55
56 /* usage of objects inside C<<1 program */
57
58 program
59 {
60 int i;
61 Animal animal[3];
62 Actions cat = catActions();
63 Actions dog = dogActions();
64
65 animal[0] = get_obj(Animal, cat, "Missy");
66 animal[1] = get_obj(Animal, cat, "Mr. Bojangles");
67 animal[2] = get_obj(Animal, dog, "Lassie");
68
69 for_range(i, 0, 2)
70 {
71 print(animal[i]->name, ":", _(talk, animal[i]));
72 }
73
74 }
This page took 0.273133 seconds and 4 git commands to generate.