Sobes.tech
Junior — Middle

Explain the concept of virtual functions in C++ and how they are implemented at runtime.

sobes.tech AI

Answer from AI

Virtual functions in C++ allow implementing polymorphism — the ability to call methods of derived classes through pointers or references to the base class.

When a function is declared with the virtual keyword in a base class, the compiler creates a table of virtual functions (vtable) for that class. This table contains pointers to functions that should be called for objects of that class.

At runtime, when a virtual function is called through a pointer or reference to the base class, the program accesses the object's vtable to determine which implementation of the function to invoke — the base version or the overridden one in the derived class. This ensures dynamic (late) binding of functions.

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* b = new Derived();
    b->show(); // Will output "Derived show" thanks to the virtual function
    delete b;
    return 0;
}

Thus, virtual functions implement a mechanism of dynamic binding, allowing the program to choose the appropriate function at runtime.