Content deleted Content added
Remove PHP from list list of languages which "treat all methods as virtual by default" as this is not the case. |
|||
Line 22:
=== C++ ===
[[Image:ClassDiagram for VirtualFunction.png|400px|thumb|right|Class Diagram of Animal]]
For example, a base class <code>Animal</code> could have a virtual function <code>
<syntaxhighlight lang="cpp">
import std;
class Animal {
// Intentionally not virtual:
void
std::
}
virtual void
};
// The class "Animal" may possess a definition for Eat if desired.
class Llama : public Animal {
// The non virtual function Move is inherited but not overridden.
void
std::cout << "Llamas eat grass!" << std::endl;
}
};
</syntaxhighlight>
This allows a programmer to process a list of objects of class <code>Animal</code>, telling each in turn to eat (by calling <code>
In C, the mechanism behind virtual functions could be provided in the following manner:
Line 51 ⟶ 54:
/* an object points to its class... */
typedef struct {
const
} Animal;
/* which contains the virtual function Animal.
typedef struct {
struct AnimalVTable {▼
void (*
/*
Since Animal.
it is not in the structure above.
*/
void
printf("<Animal at %p> moved in some way\n", (
}
/*
unlike
Eat cannot know which function (if any) to call at compile time.
Animal.
*/
void
const
if (vtable->
(*vtable->
} else {
fprintf(stderr, "'
}
}
/*
implementation of Llama.
to be called by 'void
*/
static void _Llama_eat(
printf("<Llama at %p> Llamas eat grass!\n", ( void* )(self));
}
/* initialize class */
const
const
int main(void) {
Line 98 ⟶ 101:
struct Animal animal = { &Animal };
struct Animal llama = { &Llama };
}
</syntaxhighlight>
|