C++ Containers and Polymorphism Mechanisms
BehavioralModel answerLast updated
Contrast contiguous versus node-based containers and explain static versus dynamic polymorphism in C++.
You're in a technical discussion about C++ design choices. A colleague asks you to clarify two fundamental topics:
First, compare contiguous storage containers (like std::vector) with node-based containers (like std::list).
Address these aspects:
- How elements are arranged in memory
- Cost of accessing arbitrary elements
- Performance characteristics of adding and removing elements
- Impact on CPU cache behavior
- What happens to existing iterators when the container changes
- Scenarios where each container type excels
Second, describe polymorphism in C++.
Cover:
- Static versus dynamic polymorphism and when resolution happens
- How overloading, templates, inheritance, and virtual functions enable polymorphic behavior
- Practical situations where runtime dispatch provides value
Your explanation should demonstrate understanding of both theoretical concepts and real-world performance implications.
Hints
Hint 1
Consider memory access patterns and hardware prefetching when comparing traversal performance.
Hint 2
The distinction between having an iterator and finding where to insert matters for asymptotic analysis.
Hint 3
Polymorphism is fundamentally about binding time—when does the system decide which implementation to invoke?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: C++ Containers and Polymorphism
Core Insight
Both questions probe the same underlying skill: understanding what happens at the machine level. Container choice depends on memory layout and hardware behavior, not just Big-O notation. Polymorphism is about when the system resolves which code to execute.
Contiguous vs. Node-Based Containers
Memory Organization
Contiguous containers (std::vector) allocate a single block of memory holding all elements consecutively. The container maintains the current element count and total allocated space. When space runs out, the container allocates a larger block (commonly growing by 1.5x or 2x), transfers existing elements, and releases the old block.
Node-based containers (std::list) implement a doubly-linked structure where each element resides in an individually allocated node containing forward and backward pointers. On 64-bit architectures, this adds 16 bytes of pointer overhead per element, plus allocator metadata, often consuming 6–8× the memory of contiguous storage.
Element Access Patterns
- Contiguous: Direct indexing via
operator[]executes in constant time through simple pointer arithmetic. Iterators support random access, enabling algorithms likestd::sortand binary search. - Node-based: No index operator exists. Reaching the nth element requires traversing n pointers, making it linear time. Iterators only support bidirectional movement, requiring the container's specialized
sort()member function.
Modification Costs
| Operation | Contiguous | Node-based |
|---|---|---|
| Append/remove at end | Amortized constant | Constant |
| Append/remove at front | Linear (shift all) | Constant |
| Mid-insertion with iterator | Linear (shift remainder) | Constant |
| Finding insertion point | Linear or log (if sorted) | Linear |
| Moving ranges between containers | Linear copy | Constant (splice) |
A common misconception: "node-based insertion is constant time, so it's faster for middle insertions." This constant-time guarantee applies only when you already hold the insertion iterator. Locating the position costs linear time for both container types.
For contiguous containers, the shift operation is a fast memory copy over sequential addresses. For node-based containers, the search involves chasing pointers with potential cache misses at each step. Contiguous containers often outperform even in insertion-heavy workloads unless elements are large or expensive to relocate.
CPU Cache Behavior
Contiguous storage enables sequential memory access. The CPU's hardware prefetcher anticipates upcoming addresses and loads cache lines proactively—a 64-byte cache line holds 16 four-byte integers. Node-based traversal scatters accesses across the heap, causing cache misses at nearly every step. The latency penalty (roughly 100 nanoseconds per miss) can make node-based iteration 10× slower than contiguous iteration for equivalent data.
Iterator Stability
Contiguous containers:
- Reallocation (when appending beyond capacity) invalidates every iterator, pointer, and reference
- Insertion invalidates all iterators from the insertion point onward
- Deletion invalidates iterators at and after the removed element
- Use
reserve()to prevent reallocation
Node-based containers:
- Insertion never invalidates existing iterators
- Deletion invalidates only iterators to the removed element
- Node addresses remain stable throughout the container's lifetime
Recommended Usage
Use contiguous storage as the default: sequential processing, sorted collections with binary search, numeric arrays, and general-purpose collections.
Use node-based storage when you specifically need:
- Iterator and reference stability across extensive modifications
- Constant-time splicing between containers
- Elements that cannot be moved or are prohibitively expensive to relocate
A canonical example: LRU cache implementation combining std::list with unordered_map. Hash lookup is constant time, and promoting an entry to the front uses constant-time splice.
Also consider: std::deque provides constant-time operations at both ends while preserving random access.
Polymorphism Mechanisms
Polymorphism means presenting a uniform interface that dispatches to different implementations based on types involved.
Static Polymorphism (Compile-Time)
The compiler determines the target during compilation. No runtime overhead occurs, and calls can be inlined.
Function overloading: Multiple functions share a name but differ in parameter types. The compiler selects the appropriate version based on argument types.
Templates: A single parameterized definition gets instantiated for each concrete type used. Behavior varies through the operations each type supports—compile-time duck typing. C++20 concepts formalize these requirements. The Curiously Recurring Template Pattern (CRTP) achieves "static inheritance" where a base template calls into the derived class without virtual dispatch.
Trade-offs: Binary size increases (one instantiation per type), compilation slows, and all types must be known at compile time.
Dynamic Polymorphism (Runtime)
The target is determined at runtime based on the object's actual type. Requires inheritance with virtual functions, accessed through base class pointers or references.
Implementation: Each polymorphic class maintains a vtable (virtual function table) containing function pointers. Each object stores a hidden vptr pointing to its class's vtable. Virtual calls load the vptr, index the table, and execute an indirect call.
Costs:
- One pointer per object (typically 8 bytes)
- Indirect branch per call
- Limited inlining opportunities unless the compiler devirtualizes (marking functions
finalhelps)
Critical distinction: Inheritance alone doesn't create polymorphism. Redefining a non-virtual function in a derived class merely hides the base version. Calling through a Base* still executes Base::function.
Essential Guidelines
- Declare a virtual destructor in polymorphic base classes. Deleting a derived object through a base pointer without this causes undefined behavior.
- Use
overrideto catch signature mismatches; usefinalto prevent further overriding. - Avoid object slicing: assigning a derived object to a base-type variable by value discards the derived portion, breaking virtual dispatch.
- Virtual calls inside constructors and destructors dispatch to the class currently under construction/destruction, not the most-derived class.
When Dynamic Dispatch Provides Value
Heterogeneous collections with runtime-determined types: A trading system might parse incoming messages into std::vector<std::unique_ptr<Order>> containing LimitOrder, MarketOrder, and CancelOrder instances. The execution engine calls order->execute() without type switches.
Plugin architectures: New implementations can be added without recompiling existing code (open/closed principle).
Dependency injection and testing: Code against interfaces like IDatabaseConnection, then inject mocks during testing.
Alternatives to Consider
For latency-sensitive code with a closed type set, prefer templates/CRTP or std::variant with std::visit. Both eliminate heap allocation and indirect calls while maintaining type safety.
Common Mistakes
- Assuming node-based containers are faster for insertions without considering the cost of finding the insertion point
- Forgetting that vectors typically outperform due to cache locality, even with occasional reallocations
- Omitting virtual destructors in polymorphic hierarchies
- Expecting virtual behavior from non-virtual functions or value semantics
- Ignoring
reserve()for vectors when the final size is predictable