Virtual function: Difference between revisions

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 AnimalClassAnimalVTable * classvtable;
};
 
/* which contains the virtual function Animal.Eat */
struct AnimalClassAnimalVTable {
void (*Eat)(struct Animal *self); // 'virtual' function
};
 
/*
/* Since Animal.Move is not a virtual function
itSince Animal.Move is not ina the structure above.virtual */function
it is not in the structure above.
void Move(struct Animal * self)
*/
{
void Move(const struct Animal * self) {
printf("<Animal at %p> moved in some way\n", (void void*) )(self));
}
 
/*
/* unlike Move, which executes Animal.Move directly,
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 * self) {
const struct AnimalClassAnimalVTable * classvtable = *( const void **) )(self);
{
if (vtable->Eat != NULL) {
const struct AnimalClass * class = *(const void **) self;
if (class*vtable->Eat)(self); // execute Animal.Eat
} else {
class->Eat(self); // execute Animal.Eat
fprintf(stderr, "'Eat' virtual method not implemented\n");
else
}
fprintf(stderr, "Eat not implemented\n");
}
 
/*
/* implementation of Llama.Eat this is the target function
to be called by 'void Eat(struct Animal *).' */
static to be called by 'void _Llama_eatEat(struct Animal * self).'
*/
{
static void _Llama_eat(struct Animal *self) {
printf("<Llama at %p> Llama's eat grass!\n", (void void*) )(self));
}
 
/* initialize class */
const struct AnimalClassAnimalVTable Animal = {(void *)NULL 0}; // base class does not implement Animal.Eat
const struct AnimalClassAnimalVTable Llama = { _Llama_eat }; // but the derived class does
 
int main(void) {
{
/* init objects as instance of its class */
struct Animal animal = {& &Animal };
struct Animal llama = {& &Llama };
Move(& animal); // Animal.Move
Move(& llama); // Llama.Move
Eat(& animal); // cannot resolve Animal.Eat so print "Not Implemented" to stderr
Eat(& llama); // resolves Llama.Eat and executes
}
</syntaxhighlight>