Reputation: 5639
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);
}
Upvotes: 2
Views: 390
Reputation: 28872
An easy way to understand how vtables work is to implement the same type of functionality in C using function pointers because all that a vtable is,is a table of function pointers to the concrete implementations.
Upvotes: 0
Reputation: 77722
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.
Upvotes: 0
Reputation: 131577
The explanation of the internals of virtual functions on the C++ FAQ is pretty good. You should give it a read. I think it would be better if you tried to understand it yourself and then asked your doubts.
Upvotes: 4