C++ & OOP Internals: Virtual Tables (vptr/vtable), Constructors, Diamond Inheritance & STL
Compile-time vs runtime polymorphism, vptr/vtable dispatch, base-to-derived constructor vs reverse destructor order, virtual destructors, diamond virtual inheritance, and C++ STL time complexities.
1. Runtime Polymorphism: virtual, vtable, vptr & Object Slicing
- Without
virtual(Static / Early Binding): CallingbasePtr->show()resolves at compile time using the pointer’s static type (Base::show()), even ifbasePtrpoints to aDerivedobject! - With
virtual(Dynamic / Late Binding): Compiler adds a hidden pointervptr(typically 8 bytes on 64-bit) to every polymorphic object, pointing to the class’svtableof function pointers. CallingbasePtr->show()dispatchesDerived::show()at runtime in indirect call! - Why Base Destructors MUST Be
virtual: Ifdelete basePtr;is executed when~Base()is non-virtual, only~Base()runs and~Derived()is skipped (leaking resources / undefined behavior)! - Object Slicing Trap: Passing a
Derivedobject by valuevoid f(Base b)slices off theDerivedsubobject and copies only theBasepart (sob.show()callsBase::show()even ifvirtual! Polymorphism requires pointers or referencesBase&/Base*).
#include <iostream>
struct Base {
Base() { std::cout << "B+ "; }
virtual void f() { std::cout << "Bf "; }
virtual ~Base() { std::cout << "B- "; }
};
struct Derived : Base {
Derived() { std::cout << "D+ "; }
void f() override { std::cout << "Df "; }
~Derived() override { std::cout << "D- "; }
};
int main() {
Base* p = new Derived();
p->f();
delete p; // Output: B+ D+ Df D- B-
}
2. Diamond Problem & C++ STL Container Complexities
In multiple inheritance D : public B1, public B2 where both B1, B2 inherit from A, D gets two ambiguous copies of A unless B1 and B2 inherit via virtual public A!
| STL Container | Underlying Structure | Lookup | Insert / Erase | Notes |
|---|---|---|---|---|
std::vector | Dynamic contiguous array | idx | Amortized end, mid | Best cache locality |
std::map / std::set | Red-Black Tree (ordered) | Sorted iteration | ||
std::unordered_map | Hash Table (chaining) | Avg , Worst | Avg | Requires hash + operator== |
std::priority_queue | Binary Max-Heap (by default!) | Top: | Push/Pop: | make_heap runs in |
Practice Questions on This Chapter (3)
In C++, class Derived publicly inherits from Base. Suppose Base* ptr = new Derived(); is deleted via delete ptr; when Base has a non-virtual destructor. What happens?
Which C++ mechanism resolves the Diamond Ambiguity Problem in multiple inheritance (D inherits from both B1 and B2, which both inherit from A) so D contains only one shared subobject of A?
Which C++ operators CANNOT be overloaded by a user-defined class?