#include "cll1.h"
/* This is C<<1 rewrite of object polymorphism from
- http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming */
+ http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
+
+ Of course there are easier ways to do the same thing... :-)
+ (G)2008 xChas */
def_type(Animal);
def_mem(Actions)
{
- void method(init) (Animal self, str name);
str method(talk) (Animal self);
};
char *name;
};
-Animal construct(Animal) (Animal self, str name)
+construct(Animal) (Animal self, str name)
{
self->name = name;
return self;
}
-str cat_talk(Animal self)
+/* implementation of methods */
+
+str catTalk(Animal self)
{
return "Meow!";
}
-str dog_talk(Animal self)
+str dogTalk(Animal self)
{
return "Arf! Arf!";
}
-Actions cat_actions(void)
+/* registration of methods to object interface */
+
+Actions catActions(void)
{
- Actions this=get_mem(Actions);
- this->talk = cat_talk;
+ Get_mem(this, Actions);
+
+ this->talk = catTalk;
return this;
}
-Actions dog_actions(void)
+Actions dogActions(void)
{
- Actions this=get_mem(Actions);
- this->talk = dog_talk;
+ Get_mem(this, Actions);
+
+ this->talk = dogTalk;
return this;
}
+/* usage of objects inside C<<1 program */
+
program
{
int i;
Animal animal[3];
- Actions cat = cat_actions();
- Actions dog = dog_actions();
+ Actions cat = catActions();
+ Actions dog = dogActions();
animal[0] = get_obj(Animal, cat, "Missy");
animal[1] = get_obj(Animal, cat, "Mr. Bojangles");
for_range(i, 0, 2)
{
- printf("%s: %s\n", animal[i]->name, _(talk, animal[i]));
+ print(animal[i]->name, ":", _(talk,animal[i]));
}
}