I heard lots of times virtual function is usually implemented using a vtable. But I actually don’t know actually how its implemented and how it works.
edit
I didn’t actually get this code: How can it be rewritten. Can someone explain this in detail please.
Finally, let’s see how the compiler implements a call to a virtual function. Your code might look like this:
// Your original C++ code
void mycode(Base* p)
{
p->virt3();
}
The compiler has no idea whether this is going to call Base::virt3() or Der::virt3() or perhaps the virt3() method of another derived class that doesn’t even exist yet. It only knows for sure that you are calling virt3() which happens to be the function in slot #3 of the v-table. It rewrites that call into something like this:
// Pseudo-code that the compiler generates from your C++
void mycode(Base* p)
{
p->__vptr[3](p);
}
The common implementation is to have one pointer at the beginning of every instance of an object that points to a vtable. There is one vtable per class, so if you have a class A and class B, there will be one table for each.
The vtable essentially has a bunch of function pointers, so if class A has two virtual functions, foo() and bar(), the table will have pointers to both. If class B overrides those two functions, it will have its versions of foo() and bar() at the same offsets.