Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using virtual tables?

sobes.tech AI

Answer from AI

Virtual tables (vtable) are a mechanism in object-oriented programming used to implement dynamic polymorphism (virtual functions).

Advantages:

  • Allow calling methods of derived classes through a pointer or reference to the base class.
  • Provide flexibility and extensibility of code.
  • Simplify support and addition of new classes without modifying existing code.

Disadvantages:

  • Slight decrease in performance due to an additional level of indirect function calls.
  • Increase in object size due to the pointer to the virtual table.
  • Complexity of implementation and understanding for beginners.

Example in C++:

class Base {
public:
    virtual void foo() { std::cout << "Base" << std::endl; }
};

class Derived : public Base {
public:
    void foo() override { std::cout << "Derived" << std::endl; }
};

Base* b = new Derived();
b->foo(); // Calls Derived::foo thanks to vtable
What are the advantages and disadvantages of using… - sobes.tech