C++ Contiguous vs Node Containers and Polymorphic Dispatch

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

In a C++ systems engineering interview, walk through two core language and standard-library design topics:

  1. Contiguous resizable buffers vs. node-linked sequences: Contrast std::vector<T> against std::list<T> across heap storage geometry and per-element overhead, indexed lookup complexity and iterator categories, asymptotic versus real-world costs of inserting or erasing elements at endpoints and interior positions, CPU cache-line utilization and hardware prefetching, lifetime validity of iterators/pointers/references across container mutations, and concrete engineering scenarios that call for each container.
  2. Polymorphism in C++: Define what polymorphic code achieves, contrast static compile-time resolution against dynamic runtime dispatch, explain how overload sets, templates, class inheritance, and virtual member functions fit into those two mechanisms, and describe architectural situations where runtime indirection pays for itself in production systems.

Scope & Expectations

  • Quantify memory overhead and hardware cache effects (such as 64-byte cache lines versus dependent pointer chasing) to explain why asymptotic Big-O alone can mislead container choice.
  • State precise C++ iterator, pointer, and reference invalidation rules—including capacity reallocation on std::vector and splicing stability on std::list.
  • Distinguish compile-time monomorphization and overload resolution from vtable/vptr dynamic dispatch, highlighting essential C++ safety practices (virtual destructors, override, avoiding object slicing) and practical trade-offs.

Step-by-step walkthrough

  1. Memory layout: one contiguous block vs scattered heap nodes

    A dynamic array (std::vector<T>) stores all of its elements side by side in one contiguous heap allocation, managed by a small three-word header (data pointer, size, and capacity, 24 bytes on 64-bit platforms):

    • size() is how many elements are currently constructed and live.
    • capacity() is how many elements fit in the allocated block before a reallocation is needed; the slots between size() and capacity() are raw uninitialized spare capacity.

    A doubly linked list (std::list<T>) stores each element in its own separate heap-allocated node alongside two pointers (prev and next), so neighboring elements can live far apart in RAM:

    std::vector<int> (size = 3, capacity = 4):
      stack header [ data* | size=3 | cap=4 ]
                       |
                       v
      heap block:    [ 10 | 20 | 30 | (spare) ]   <-- one contiguous allocation
    
    std::list<int> (size = 3):
      sentinel [ next* | prev* ]
                   |
                   v
      node A @ 0x7100: [ prev | next | 10 | pad ] ---> node B @ 0x4a80: [ prev | next | 20 | pad ]
                                                                               |
                                                                               v
                                                       node C @ 0x9f20: [ prev | next | 30 | pad ]
    

    Worked memory comparison for 1,000,000 int values (4 bytes each) on 64-bit C++:

    std::vector<int> (with 2x capacity doubling, capacity = 2^20 = 1,048,576):
      1,048,576 × 4 bytes                                           ≈  4.2 MB  (21 heap allocations total)
      (or exactly 4.0 MB in 1 allocation if v.reserve(1'000'000) is called up front)
    
    std::list<int>:
      1,000,000 nodes × (8-byte prev + 8-byte next + 4-byte int + 4-byte alignment padding = 24 bytes)
                                                                    = 24.0 MB raw node structs
      With standard allocator chunk rounding/metadata (32 B/node)   ≈ 32.0 MB  (1,000,000 allocations!)
    

    For small elements, std::list uses roughly 6x–8x more memory and stresses the heap allocator with a million tiny allocations.

  2. Random access and iterator categories

    Because a vector's elements sit side by side in memory, the address of element i is computed in one arithmetic formula: data() + i * sizeof(T). Indexing v[i] (unchecked) or v.at(i) (bounds-checked) runs in O(1) time. Vector iterators are random-access iterators—jumping it + 1000 is a single pointer addition.

    std::list intentionally omits operator[] because reaching the i-th element requires following i separate next pointers in O(i) time. List iterators are bidirectional iterators (supporting only ++it and --it), which restricts standard algorithms:

    • std::sort requires random-access iterators and will not compile on std::list; you must call the member function list.sort() (an O(n log n) merge sort that relinks node pointers without moving elements).
    • std::lower_bound (binary search) on a sorted std::vector runs in O(log n) time. Calling std::lower_bound on a sorted std::list performs O(log n) element comparisons, but walks next pointers O(n) times to find the midpoints—degrading to linear time!
    std::vector<int> v = {10, 20, 30, 40};
    int third_vec = v[2];                       // O(1): base_ptr + 2 * sizeof(int)
    
    std::list<int> l = {10, 20, 30, 40};
    int third_list = *std::next(l.begin(), 2);  // O(i): chases two 'next' pointers
    
  3. Insertion and deletion trade-offs

    Operation std::vector<T> std::list<T>
    Append / pop at back (push_back, pop_back) Amortized O(1) / O(1) O(1)
    Insert / pop at front O(n): shifts all n elements O(1) (push_front, pop_front)
    Insert / erase at middle given an iterator O(n − pos): shifts trailing elements O(1): updates 4 neighbor pointers
    Search for a value + insert/erase O(n) scan + O(n) shift = O(n) O(n) scan + O(1) relink = O(n)
    Transfer nodes between containers O(k) moves + source tail shift splice: O(1) for 1 node or whole list; O(k) for k-node sub-range from another list

    (Note on splice: since C++11, std::list::size() must be O(1), so splicing a [first, last) sub-range from a different list counts those k nodes in O(k) to update both sizes; splicing within the same list stays O(1).)

    Why vector::push_back is amortized O(1) (constant average cost per operation): When size() == capacity(), vector allocates a block larger by a constant factor (2x in GCC's libstdc++ and Clang's libc++; 1.5x in MSVC), moves existing elements over, and frees the old buffer. Over 1,000,000 pushes with 2x doubling, reallocations happen only at powers of two (1, 2, 4, ..., 524,288), moving 1 + 2 + 4 + ... + 524,288 = 1,048,575 elements in total—roughly 1 element move per push_back on average! (If vector grew by a fixed +100 slots each time, total moves would sum an arithmetic series to O(n²).)

    Two practical C++ nuances interviewers listen for:

    • list's O(1) middle insert/erase only applies when you already hold the iterator. If you have to scan from begin() to find where to insert, both containers are O(n).
    • Mark move constructors noexcept. During reallocation, std::vector only moves elements if T's move constructor is noexcept (or T is not copyable); otherwise it copies them so the old buffer stays intact if an exception is thrown partway through.
    • Bulk removal on a vector: erasing elements in a loop one by one is O(n²); use the erase-remove idiom (std::erase / std::erase_if in C++20) to compact kept elements in a single O(n) pass:
    // Moves non-zero elements left in one O(n) pass, then trims the tail once:
    v.erase(std::remove(v.begin(), v.end(), 0), v.end());  // C++20: std::erase(v, 0);
    
  4. Cache locality: why vector often beats list even on O(n) inserts

    Modern CPUs do not fetch individual 4-byte integers from main memory (DRAM); they fetch fixed 64-byte cache lines into fast CPU cache:

    64-byte CPU cache line loaded from std::vector<int>:
      [ v[0] | v[1] | v[2] | v[3] | ... | v[14] | v[15] ]   --> 16 useful ints per fetch!
      + Hardware prefetcher detects sequential addresses and pre-loads the next cache lines.
    
    64-byte CPU cache line loaded from std::list<int>:
      [ prev* | next* | val | pad | unrelated heap data... ] --> 1 useful int per fetch!
      + Address of node i+1 lives INSIDE node i, stalling the CPU on each pointer load.
    

    An L1 cache hit takes roughly ~1 nanosecond (~3–4 CPU cycles), whereas a main-memory cache miss takes roughly ~70–100 nanoseconds (~200–300 cycles). Scanning a scattered std::list is a chain of dependent loads—the CPU cannot even issue the memory read for node i + 1 until node i arrives from RAM—defeating both out-of-order execution and the hardware prefetcher (circuitry that predicts sequential address strides and fetches upcoming cache lines ahead of time).

    As a result, for small or trivially movable types (int, double, small structs), inserting into the middle of a std::vector of thousands of elements is frequently faster in wall-clock time than searching and inserting into a std::list: a sequential vector scan plus a contiguous memmove runs at peak cache bandwidth, while the list stalls on cache misses during its walk.

  5. Iterator invalidation rules and dangling-reference bugs

    Iterator invalidation happens when modifying a container moves or destroys elements so existing iterators, raw pointers, or C++ references no longer point to valid objects; dereferencing them afterward causes undefined behavior (crashes, silent data corruption, or heisenbugs).

    Mutating operation What std::vector invalidates What std::list invalidates
    push_back / insert with reallocation (size == capacity) Every iterator, pointer, and reference Never reallocates (none)
    push_back without reallocation (size < capacity) Only end() (elements do not move) None
    insert / erase without reallocation at pos Everything at or after pos (including end()) insert: none; erase: only the erased element(s)
    reserve(new_cap) when new_cap > capacity() Every iterator, pointer, and reference Not applicable
    splice, list::sort, reverse Not applicable None (nodes are relinked in place!)

    The most common production C++ bug with std::vector is holding an element reference across a push_back or incrementing an invalidated iterator after erase:

    std::vector<int> v = {1, 2, 3};
    int& first = v[0];
    v.push_back(4);  // Reallocates if capacity was 3 -> 'first' now dangles into freed RAM!
    // int bad = first;  // Undefined behavior!
    
    // Safe single-element loop erasure: erase() returns the iterator to the next element
    for (auto it = v.begin(); it != v.end(); ) {
        if (*it % 2 == 0) {
            it = v.erase(it);
        } else {
            ++it;
        }
    }
    
  6. Typical use cases: when to pick vector vs list

    • Choose std::vector as your default sequential container (95%+ of cases): dense computation, order-book price levels, sorting, binary search, stacks, serialization buffers, and interoperating with C APIs expecting (ptr, len) via v.data().
    • Choose std::list only when you specifically need pointer/iterator stability or node splicing:
      1. Stable iterators stored in an index, such as an LRU (Least Recently Used) cache combining std::unordered_map<Key, std::list<Node>::iterator> with a std::list<Node>: every cache hit moves the accessed node to the front in O(1) via list.splice(list.begin(), list, it) without invalidating any iterator in the hash map.
      2. O(1) splicing of whole queues between subsystems (e.g., detaching a batch of log entries from a lock-protected producer list into a consumer list in a few pointer swaps).
      3. Non-movable, non-copyable objects (e.g., structs containing a std::mutex or std::atomic) constructed in place via emplace_back, since vector reallocation requires moving or copying elements.
    • Keep nearby containers in mind: std::deque provides O(1) push_front and push_back plus O(1) random access using fixed-size chunks (preserving element references on end-pushes, though invalidating iterators), and std::forward_list cuts node overhead to one pointer when backward traversal is unnecessary.
  7. Compile-time polymorphism: overloading and templates

    Polymorphism ("many forms") lets a single interface operate on multiple concrete types. C++ separates polymorphism by when the target function is chosen.

    In compile-time (static) polymorphism, the compiler resolves the exact function to call from the expressions' static types (the types known in source code at compile time). There is zero runtime dispatch overhead, and the compiler can inline the callee directly into hot loops:

    1. Function and operator overloading (ad-hoc polymorphism): multiple functions share one name with different parameter lists (abs(int) vs abs(double), or operator+ on numbers vs strings), selected by compile-time overload resolution.
    2. Templates (parametric polymorphism): a single function or class template works for any type T satisfying the syntactic operations used inside it (constrained cleanly at the signature in C++20 using concepts). The compiler generates specialized machine code per concrete type T (monomorphization), trading faster execution for longer compile times and larger binaries if instantiated across many types.
    3. CRTP (Curiously Recurring Template Pattern): a class Derived inherits from Base<Derived> so Base can call static_cast<Derived*>(this)->impl() at compile time without virtual overhead.
    // Function overloading: picked at compile time from the argument type
    void log_value(int x)                { std::cout << "int: " << x << '\n'; }
    void log_value(const std::string& s) { std::cout << "str: " << s << '\n'; }
    
    // Function template: compiler stamps out a separate version per Shape type
    template <typename Shape>
    double sum_areas(const std::vector<Shape>& shapes) {
        double total = 0.0;
        for (const auto& s : shapes) {
            total += s.area();  // direct, inlinable call — no virtual table lookup
        }
        return total;
    }
    

    Limitation: std::vector<Shape> is homogeneous—every element must be the exact same compile-time type Shape. Static polymorphism alone cannot store mixed Circle and Square objects in one vector or instantiate a handler chosen from a runtime config file.

  8. Runtime polymorphism: inheritance, virtual functions, and practical use

    In runtime (dynamic) polymorphism, a base class declares methods virtual, derived classes override them (override), and callers invoke them through a base-class pointer or reference (Shape*, const Shape&). The program chooses which override to execute at runtime based on the object's true dynamic type (dynamic dispatch).

    Compilers implement dynamic dispatch using a vtable (a per-class read-only table of function pointers) and a hidden vptr (an 8-byte pointer stored at the start of every polymorphic object instance):

    Heap objects pointed to by std::vector<std::unique_ptr<Shape>>:
    
      shapes[0] ---> [ vptr* | radius = 2.0 ]        ---> Circle vtable:
                                                            [0] &Circle::~Circle
                                                            [1] &Circle::area
    
      shapes[1] ---> [ vptr* | side = 3.0 ]          ---> Square vtable:
                                                            [0] &Square::~Square
                                                            [1] &Square::area
    
    struct Shape {
        virtual double area() const = 0;  // pure virtual ('= 0') makes Shape an abstract interface
        virtual ~Shape() = default;       // MUST be virtual whenever deleting via Shape*!
    };
    
    struct Circle final : Shape {
        double radius;
        explicit Circle(double r) : radius(r) {}
        double area() const override { return 3.141592653589793 * radius * radius; }
    };
    
    struct Square final : Shape {
        double side;
        explicit Square(double s) : side(s) {}
        double area() const override { return side * side; }
    };
    

    Essential C++ rules for runtime polymorphism:

    • Always give polymorphic base classes a virtual destructor: without virtual ~Shape(), deleting a Circle through a Shape* (std::unique_ptr<Shape>) triggers undefined behavior and leaks resources owned by Circle.
    • Avoid object slicing: passing or storing a derived object by value (Shape s = Circle(2.0);) copies only the Shape subobject, stripping off Circle's fields and vptr. Always pass polymorphic objects by reference or smart pointer.
    • Mark overrides override (and leaf classes final): override turns signature mismatches (like forgetting const) into compile errors instead of silent overload hiding, while final helps the compiler devirtualize calls back into direct inlined calls when the concrete type is visible.
    • No dynamic dispatch into derived classes inside constructors/destructors: while Base::Base() is running, the derived members are not constructed yet (or in ~Base(), already destroyed), so virtual calls resolve to Base's own version.

    When dynamic dispatch is useful in practice: Use virtual interfaces when concrete types arrive at runtime (message handlers selected from network headers, UI widgets, AST nodes), when maintaining open heterogeneous collections or plugin systems where new derived types are added without recompiling existing callers, or at architectural boundaries for dependency injection (swapping a live ExchangeGateway with a MockGateway in unit tests). When the set of types is small, fixed, and known at compile time, std::variant<Circle, Square> with std::visit achieves runtime dispatch without per-object heap allocations, keeping mixed values contiguous inside a single std::vector!

Intuition & how it works

Picture std::vector as a row of numbered apartment mailboxes bolted onto one wall, and std::list as a scavenger hunt where each envelope sits in a different building across town with a note pointing to the next address. With the mailbox wall (vector), jumping straight to box #500 is instant math (start + 500 * box_width), and your mail carrier loads 16 neighboring boxes at a time in one armful (cache locality). With the scavenger hunt (list), reaching #500 forces 500 separate trips across town, though slipping a new envelope between two envelopes you are already holding only requires rewriting two address notes instead of sliding every later mailbox over.

A beginner trap is trusting textbook Big-O in isolation—assuming std::list is faster whenever a program inserts or deletes in the middle. On real CPUs, finding where to insert in a std::list stalls on slow main-memory pointer hops (~70–100 ns per cache miss vs ~1 ns in L1 cache), whereas scanning a std::vector and shifting contiguous ints with memmove streams smoothly through 64-byte CPU cache lines. Similarly, C++ polymorphism ("one interface, many types") splits into two tools: compile-time polymorphism (templates and overloading, like stamping custom wrenches in the factory with zero runtime cost) versus runtime polymorphism (virtual functions, like a universal socket adapter that checks which attachment is plugged in at runtime via a hidden function-pointer table).

Walk through two concrete mini-examples to compare both ideas:

  • Inserting 25 into {10, 20, 30, 40}: std::vector scans [10, 20, 30, 40] inside a single 64-byte cache line, shifts 30 and 40 four bytes right, and writes 25 at index 2 (invalidating iterators from index 2 onward, or all iterators if size == capacity triggers a 2x buffer reallocation). std::list chases heap pointers node by node to reach 30, allocates a new 24-byte node [prev | next | 25], and rewires four neighbor pointers—slower to reach the spot, but every existing iterator into the list stays valid.
  • Computing area() on shapes: template <typename S> double twice(const S& s) { return 2 * s.area(); } resolves s.area() at compile time with zero indirection, whereas std::vector<std::unique_ptr<Shape>> holding a Circle(2) and Square(3) follows each object's hidden vptr at runtime to its class vtable to dispatch Circle::area() (12.57) and Square::area() (9.0).

Key points

  • Memory layout and overhead: std::vector<T> owns one contiguous heap block with spare capacity(); std::list<T> allocates one heap node per element containing prev and next pointers. For 1,000,000 4-byte ints on 64-bit C++, vector uses ~4.2 MB in ~21 allocations versus ~24–32 MB across 1,000,000 allocations for list.
  • Random access and algorithms: vector provides O(1) indexing (data() + i * sizeof(T)) and random-access iterators, enabling O(n log n) std::sort and O(log n) std::lower_bound binary search; list has O(i) traversal and bidirectional iterators (++/-- only), requiring member list::sort().
  • Insertion and erasure trade-offs: vector::push_back runs in amortized O(1) time (doubling capacity moves roughly 1 element per push on average, or 0 moves after reserve(n)), while middle insert/erase shifts n − pos elements in O(n); list gives O(1) insert, erase, and splice only when you already hold an iterator to the target node.
  • Cache locality dominates small elements: a 64-byte CPU cache line packs 16 contiguous ints and lets the hardware prefetcher preload upcoming lines, whereas list traversal performs dependent pointer loads that frequently miss cache.
  • Iterator invalidation: vector invalidates all iterators, pointers, and references on reallocation, and invalidates those at or after pos on non-reallocating insert/erase (only end() on non-reallocating push_back); list never invalidates iterators or references except to erased nodes.
  • Default to vector, specialize with list: use vector almost everywhere; pick list when an external map stores persistent node iterators (like an LRU cache using unordered_map + list::splice), when splicing whole queues in O(1), or when holding non-movable objects.
  • Compile-time vs runtime polymorphism: function/operator overloading and templates resolve calls at compile time from static types (enabling inlining and zero memory overhead, constrained cleanly via C++20 concepts, but limited to homogeneous containers), whereas inheritance + virtual functions dispatch at runtime on the dynamic type via an object vptr and class vtable (enabling open heterogeneous collections, plugins, and runtime interfaces at the cost of an indirect call and an 8-byte vptr per object).

Common mistakes

  • Claiming std::list is faster for random middle insertions without already having the iterator. If you have to search linearly to find the insertion point first, vector's cache-friendly scan + memmove usually beats list's pointer-chasing walk for small or cheap-to-move types.
  • Keeping pointers, references, or iterators into a std::vector across push_back or insert. Any reallocation frees the old buffer and leaves int& ref = v[0] dangling into freed memory (undefined behavior).
  • Confusing v.reserve(n) with v.resize(n). reserve(n) only pre-allocates raw spare capacity() while size() stays 0, so indexing v[0] after reserve without pushing or resizing is out-of-bounds undefined behavior.
  • Omitting virtual ~Base() = default; on a polymorphic base class. Deleting a Derived instance through a Base* (including std::unique_ptr<Base>) without a virtual destructor is undefined behavior and skips Derived's destructor.
  • Object slicing by passing or storing polymorphic types by value. Writing std::vector<Shape> or void draw(Shape s) copies only the Base subobject and discards derived data and overrides; use references (const Shape&) or smart pointers (std::unique_ptr<Shape>).
  • Calling virtual methods inside a constructor expecting the derived override to run. During Base::Base(), the Derived part is not yet initialized, so C++ intentionally binds virtual calls to Base's implementation.

Follow-up questions

  • How does std::deque balance endpoint growth, indexed lookup, and reference lifetime compared with std::vector and std::list? std::deque stores elements in an indexed map of fixed-size contiguous chunks (such as 512 bytes or 4 KiB per block), providing O(1) push_front and push_back alongside O(1) random-access indexing (d[i]). Unlike vector, pushing at either end of a deque never reallocates or moves existing elements—so C++ pointers and references to existing elements remain valid, even though iterators are invalidated—at the cost of double pointer indirection on indexing and no single contiguous data() buffer for C APIs.
  • Where does the real performance cost of a virtual method call come from on modern CPUs, and when can the compiler remove it? A virtual call loads the object's vptr, loads the target function pointer from the vtable, and executes an indirect jump; on modern CPUs with warm branch predictors, that indirect jump adds only a few cycles unless mixed types cause mispredictions, but the bigger cost is blocking compiler inlining and SIMD loop vectorization. Marking leaf classes or overrides final and enabling Link-Time Optimization (LTO) lets the compiler prove the concrete dynamic type (devirtualization) and turn the virtual call back into a direct, inlined call.
  • In what scenarios is std::variant paired with std::visit preferable to a virtual base-class hierarchy? Choose std::variant<Circle, Square> when the set of alternative types is closed and known at compile time: a std::vector<std::variant<Circle, Square>> stores heterogeneous shapes inline in one contiguous cache-friendly buffer with value semantics, zero per-object heap allocations, and no vptr overhead (though each slot is sized to the largest alternative plus a tag byte). Choose virtual inheritance when the set of types is open (such as plugins or independently compiled modules) or when alternative sizes vary wildly so padding every element to the largest type would waste memory.

Follow-up questions

Similar questions

More Intercontinental Exchange interview questions

All 2 Intercontinental Exchange questions →