#3 refining of object macros
[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
96ec74e5 9def_type(Animal);
10
b27abb8a 11def_mem(Actions)
097bac9a 12{
96ec74e5 13 str method(talk) (Animal self);
097bac9a 14};
15
96ec74e5 16def_obj(Animal)
097bac9a 17{
b27abb8a 18 interface(Actions);
19 char *name;
20};
097bac9a 21
24cfa6bd 22construct(Animal,Actions) (Animal self, str name)
1a8d78d9 23{
24 self->name = name;
25 return self;
26}
27
96ec74e5 28/* implementation of methods */
29
30str catTalk(Animal self)
097bac9a 31{
b27abb8a 32 return "Meow!";
097bac9a 33}
34
96ec74e5 35str dogTalk(Animal self)
097bac9a 36{
b27abb8a 37 return "Arf! Arf!";
097bac9a 38}
39
96ec74e5 40/* registration of methods to object interface */
41
42Actions 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 50Actions 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 60program
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 {
96ec74e5 73 print(animal[i]->name, ":", _(talk,animal[i]));
b27abb8a 74 }
097bac9a 75}
This page took 0.216915 seconds and 4 git commands to generate.