Virtual Functions V‐Table and Dynamic Dispatch - Rybd04/2143-OOP GitHub Wiki

Definition

Virtual Functions (V-Table and Dynamic Dispatch)

A function that can be overridden in a derived class. It allows a program to call the correct version of the function based on the type of the object being pointed to, not the type of the pointer.

Explanation

When a class has virtual functions, C++ creates a special table called the V-Table. This table holds pointers to the actual functions of the class.

Basic Code Example

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
    virtual void speak() {  // Virtual function
        cout << "Animal speaks!" << endl;
    }
};

// Derived class
class Dog : public Animal {
public:
    void speak() override {  // Override the virtual function
        cout << "Woof! Woof!" << endl;
    }
};

// Derived class
class Cat : public Animal {
public:
    void speak() override {  // Override the virtual function
        cout << "Meow! Meow!" << endl;
    }
};

int main() {
    Animal* animal1 = new Dog();  // Base pointer to derived object
    Animal* animal2 = new Cat();  // Base pointer to another derived object

    animal1->speak();  // Woof! Woof! (calls Dog's speak)
    animal2->speak();  // Meow! Meow! (calls Cat's speak)

    delete animal1;
    delete animal2;
    return 0;
}

Image

image

Additional Resources

https://medium.com/@satyadirisala/demystifying-dynamic-dispatch-a-deep-dive-into-virtual-functions-vptr-and-vtable-9574c1ad9bed https://pabloariasal.github.io/2017/06/10/understanding-virtual-tables/

⚠️ **GitHub.com Fallback** ⚠️