I was looking for some information about virtual tables, but I can’t find anything that is easy to understand.
Can somebody give me good examples with explanations?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Without virtual tables you wouldn’t be able to make runtime polymorphism work since all references to functions would be bound at compile time. A simple example
Inside the function
callF, you only know thatopoints to aBaseobject. However, at runtime, the code should callDerived::f(sinceBase::fis virtual). At compile time, the compiler can’t know which code is going to be executed by theo->f()call since it doesn’t know whatopoints to.Hence, you need something called a “virtual table” which is basically a table of function pointers. Each object that has virtual functions has a “v-table pointer” that points to the virtual table for objects of its type.
The code in the
callFfunction above then only needs to look up the entry forBase::fin the virtual table (which it finds based on the v-table pointer in the object), and then it calls the function that table entry points to. That might beBase::fbut it is also possible that it points to something else –Derived::f, for instance.This means that due to the virtual table, you’re able to have polymorphism at runtime because the actual function being called is determined at runtime by looking up a function pointer in the virtual table and then calling the function via that pointer – instead of calling the function directly (as is the case for non-virtual functions).