why virtual table matters?

To implement dynamic binding, for each class, there is a virtual table to store addr of each function. Why this indirection is needed? can we just have the class directly store the ptr to the correct function?


tag: c++, virtual function
can we just have the class directly store the ptr to the correct function?
Yes. That's what the virtual table does.
The virtual table is needed because, with dynamic binding, the compiler can't know the actual type of an object by looking at the type of a pointer to it.
1
2
3
4
5
6
7
Animal *animal = (rand() % 2) ? new Dog : new Cat;
animal->emit_sound();

//Translated (approx.):
InternalAnimal *p = malloc(max(sizeof(Dog), sizeof(Cat)) + sizeof(vtable));
p->vtable[EMIT_SOUND] = (rand() % 2) ? Dog::emit_sound : Cat::emit_sound;
p->vtable[EMIT_SOUND]();
Topic archived. No new replies allowed.