C++ Virtual Functions, VTable, VPtr Internals & Pure Virtual Abstract Classes

When an object is manipulated through a pointer or reference to its base class, C++ uses Virtual Functions to ensure the derived class's implementation is executed at runtime.

C++ VTable and VPtr Dynamic Dispatch Architecture
Figure 11: Dynamic Dispatch Mechanics: Object Instance vptr → Class VTable Function Array

Abstract Classes & Pure Virtual Functions

#include <iostream>

// Abstract Base Class (Cannot be directly instantiated!)
class Shape {
public:
    // Pure virtual function
    virtual void draw() const = 0;

    // MANDATORY: Virtual Destructor
    virtual ~Shape() { std::cout << "Shape destroyed\n"; }
};

class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a smooth Circle\n";
    }
    ~Circle() override { std::cout << "Circle cleaned up\n"; }
};

int main() {
    Shape* s = new Circle();
    s->draw(); // Dispatches dynamically to Circle::draw()!

    delete s;  // Safely calls Circle destructor then Shape destructor!
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. How does the VTable (Virtual Method Table) work in C++?

For every class containing virtual functions, the compiler creates a static array of function pointers called the VTable. Each object instance of that class contains an invisible pointer (vptr, 8 bytes) pointing to this VTable. When a virtual function is called via a base pointer, C++ dereferences vptr to look up the correct derived address.

Q2. Why MUST base class destructors be declared 'virtual'?

If a base destructor is not virtual, calling 'delete basePtr' on a derived object calls ONLY the base destructor. The derived class destructor is skipped, leaking all dynamic memory and resources held by the child class.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Polymorphism

Overview of dynamic vs static dispatch.

Constructors & Destructors

Understanding destructor chains.

Dynamic Cast

How dynamic_cast uses VTable RTTI information.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!