apply()
code existed and was compiled long before class Circle was createdapply()
code in this case must call Circle::draw()
We can solve any problem by introducing an extra level of indirection
All problems in computer science can be solved by another level of indirection, except for the problem of too many layers of indirection
method[0]
for the first virtual methodmethod[1]
for the second virtual methodShape* p = new Shape(); p->draw();
Shape* p
points to the new Shape objectdraw()
is the first entry in the vtablep->draw()
conceptually becomes p->vptr->method[0]()
as the first entry in the vtable points to the function for Shape::draw()
Shape* p = new Circle(); p->draw();
Shape* p
points to the new Circle objectdraw()
is the first entry in the vtablep->draw()
conceptually becomes p->vptr->method[0]()
as the first entry in the vtable points to the function for Circle::draw()
Circle::draw()
p->draw()
Circle
on the base class Shape
. Changes to the vtable of the class Shape
(e.g., add, remove, or reorder virtual methods) change the vtable of the class Circle
.Shape
class (e.g., apply()
) can only call class Shape
methods, i.e., it cannot call the method Circle::resize()
.