Content deleted Content added
Tags: Mobile edit Mobile web edit Advanced mobile edit |
→Example: reworked C example a bit. |
||
Line 52:
/* an object points to its class... */
struct Animal {
const struct
};
/* which contains the virtual function Animal.Eat */
struct
void (*Eat)(struct Animal *self); // 'virtual' function
};
/*
it is not in the structure above.
void Move(struct Animal * self)▼
*/
printf("<Animal at %p> moved in some way\n", (
}
/*
Eat cannot know which function (if any) to call at compile time.
Animal.Eat can only be resolved at run time when Eat is called.
*/ void Eat(struct Animal *
if (vtable->Eat != NULL) {
▲ const struct AnimalClass * class = *(const void **) self;
} else {▼
fprintf(stderr, "'Eat' virtual method not implemented\n");▼
▲ else
}
▲ fprintf(stderr, "Eat not implemented\n");
}
/*
*/
static void _Llama_eat(struct Animal *self) {
printf("<Llama at %p> Llama's eat grass!\n", (
}
/* initialize class */
const struct
const struct
int main(void) {
/* init objects as instance of its class */
struct Animal animal = {
struct Animal llama = {
Move(&
Move(&
Eat(&
Eat(&
}
</syntaxhighlight>
|