Explain the concept of a virtual table and its role in implementing polymorphism in object-oriented programming.
sobes.tech AI
Answer from AI
A virtual table (vtable) is a data structure used in object-oriented programming languages to support dynamic (runtime) polymorphism. It contains pointers to functions (methods) that can be overridden in derived classes.
When an object calls a virtual method, the program uses the vtable to determine which implementation of the method to invoke — the one from the base class or the overridden one in the derived class. This allows the same interface to be used for different object types, providing flexibility and extensibility of the code.
Example: if there is a base class Animal with a virtual method sound(), and classes Dog and Cat override this method, then calling sound() through a pointer to Animal will invoke the method of the respective subclass thanks to the vtable.