* richard pickworth:
What does "virtual" mean?
Consider
struct A{ virtual void foo(){} };
struct B: A {}
struct C: B { virtual void foo(){} };
and
int main()
{
A* a = new A; A* b = new B; A* c = new C;
a->foo();
b->foo();
c->foo();
delete c; delete b; delete a;
}
For the a->foo() call A::foo is executed.
For the b->foo() call A::foo is executed. Since B doesn't provide
any foo() implementation there isn't any other possibility. 'virtual'
or not.
For the c->foo() call the result depends on whether foo() is virtual
or not. The statically known type for c is A*, a pointer to an A-object.
So if foo() wasn't virtual A::foo() would have been executed, according
to the type of object known at this place in the program text at compile
time.
But foo() is 'virtual' in A, and therefore also in all derived
classes, so the c->foo() results in a check of the _dynamic_ (run-time)
type of the object pointed to by c, which here is C, and the function
executed is _as if_ a search for foo() started in class C and then went up
the base class chain until found; here foo() is found in class C.
A typical C++ compiler will emit equivalent machine code that completely
avoid the search up the base class chain, by using table look-ups.