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