Explain the concept of a virtual function table in object-oriented programming.
sobes.tech AI
Answer from AI
The virtual function table (vtable) is a mechanism used in C++ to implement polymorphism through virtual functions. When a class contains virtual methods, the compiler creates a special table of pointers to these functions. Each object of such a class contains a hidden pointer to this table.
When calling a virtual function through a pointer or reference to the base class, the program accesses the vtable to determine which version of the function to call — the base or the overridden one in the derived class. This allows for dynamic (runtime) polymorphism.
Example:
#include <iostream>
class Base {
public:
virtual void show() { std::cout << "Base show" << std::endl; }
};
class Derived : public Base {
public:
void show() override { std::cout << "Derived show" << std::endl; }
};
int main() {
Base* obj = new Derived();
obj->show(); // Calls Derived::show thanks to vtable
delete obj;
return 0;
}
Here, the call obj->show() during runtime determines that the method from the Derived class should be called, not from Base, thanks to the virtual function table.