Reading C++: Linked List Bug and Polymorphic Dispatch Tracing
BehavioralModel answerLast updated
Find the bug in a linked list insertion function and predict the output of a C++ program involving virtual functions, constructors, and slicing.
You are given two short C++ programs to analyze without running them.
Part 1: Debug the Linked List Insertion
The function insertAfter(prev, value) should insert a new node containing value immediately after the node prev. The comments in main describe the intended list after each call.
#include <iostream>
struct Node {
int value;
Node* next;
Node(int v) : value(v), next(nullptr) {}
};
void insertAfter(Node* prev, int value) {
if (prev == nullptr) return;
Node* node = new Node(value);
prev->next = node;
}
void print(const Node* head) {
for (const Node* cur = head; cur != nullptr; cur = cur->next) {
std::cout << cur->value << (cur->next ? " -> " : "\n");
}
}
int main() {
Node* head = new Node(1);
insertAfter(head, 3); // intended: 1 -> 3
insertAfter(head, 2); // intended: 1 -> 2 -> 3
insertAfter(head->next, 4); // intended: 1 -> 2 -> 4 -> 3
print(head);
}
Your tasks:
- Predict the exact output this program produces
- Identify the bug and explain its consequences
- Provide a corrected version of
insertAfter - Discuss edge cases and potential memory issues
Part 2: Trace Polymorphic Behavior
Predict the exact output of this program, line by line. For each line of output, explain which language rule determines what gets printed.
#include <iostream>
class Base {
public:
Base() { hello(); }
virtual ~Base() = default;
virtual void hello() const { std::cout << "Base::hello\n"; }
void greet() const { std::cout << "Base::greet\n"; }
virtual void show(int x = 1) const { std::cout << "Base::show " << x << "\n"; }
};
class Derived : public Base {
public:
Derived() { hello(); }
void hello() const override { std::cout << "Derived::hello\n"; }
void greet() const { std::cout << "Derived::greet\n"; }
void show(int x = 2) const override { std::cout << "Derived::show " << x << "\n"; }
};
void byValue(Base b) { b.hello(); }
int main() {
Derived d;
Base* p = &d;
p->hello();
p->greet();
p->show();
d.show();
byValue(d);
}
Your tasks:
- Predict the complete output with exact text
- Explain the mechanism behind each line printed
- Identify which language features cause surprising behavior
- Suggest how to avoid these pitfalls in production code
Hints
Hint 1
In Part 1, trace what each insertAfter call does to the next pointers. What happens to the node created in the first call?
Hint 2
In Part 2, virtual dispatch does not work during base-class construction. The object is not yet a Derived.
Hint 3
When a Derived object is passed by value as a Base parameter, only the Base portion is copied—this is called object slicing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: The Linked List Bug
Predicted Output
1 -> 2
Step-by-Step Trace
Initial state: head points to a node with value 1 and next = nullptr.
After insertAfter(head, 3):
- A new node with value
3is created head->nextis set to point to this new node- List structure:
1 -> 3
After insertAfter(head, 2):
- A new node with value
2is created head->nextis overwritten to point to the new node with value2- The node containing
3is now unreachable (memory leak) - List structure:
1 -> 2
After insertAfter(head->next, 4):
head->nextnow points to the node with value2- A new node with value
4is created - The node with value
2has itsnextpointer set to the new node - But the node with value
4hasnext = nullptr, so the node with value3remains unreachable - Final list:
1 -> 2 -> 4
Wait—let me re-trace the third call. After the second call, head->next points to the node with value 2, and that node's next is nullptr. So insertAfter(head->next, 4) sets the 2 node's next to point to the new node 4. The output should be 1 -> 2 -> 4, not 1 -> 2.
Actually, reviewing the trace: the node containing 3 becomes unreachable after the second insertion and is never part of the final list.
Corrected prediction: 1 -> 2 -> 4
The Bug
The function fails to preserve the rest of the list. When inserting a node after prev, the new node should link to whatever prev was previously pointing to. The correct implementation:
void insertAfter(Node* prev, int value) {
if (prev == nullptr) return;
Node* node = new Node(value);
node->next = prev->next; // Link new node to the rest of the list
prev->next = node; // Link prev to the new node
}
Order matters: You must assign node->next before updating prev->next, otherwise you lose the reference to the rest of the list.
Consequences
- Lost nodes: Every insertion after the first at a given position orphans the previous node, causing memory leaks.
- Wrong list structure: The final list is missing the node with value
3entirely.
Edge Cases and Memory Management
- Null
prev: The guard clause correctly returns early. - Inserting after the tail: Works correctly since
node->nextwill be set tonullptr. - Memory leaks: The program never deallocates any nodes. A proper implementation would require a destructor or cleanup function that walks the list and deletes each node.
Part 2: Polymorphic Dispatch
Predicted Output
Base::hello
Derived::hello
Derived::hello
Base::greet
Derived::show 1
Derived::show 2
Base::hello
Line-by-Line Explanation
Line 1: Base::hello
During construction of Derived d, the Base constructor runs first and calls hello(). Even though hello() is virtual, during base-class construction the object is not yet a Derived, so the call resolves to Base::hello(). This prevents calling virtual functions on an incompletely constructed object.
Line 2: Derived::hello
After the Base constructor completes, the Derived constructor runs and calls hello(). Now the object is a Derived, so the call resolves to Derived::hello().
Line 3: Derived::hello
p is a Base* pointing to a Derived object. The call p->hello() uses virtual dispatch and resolves to Derived::hello().
Line 4: Base::greet
greet() is not virtual. The call p->greet() is resolved statically based on the pointer type, which is Base*, so it calls Base::greet(). This is name hiding, not polymorphism.
Line 5: Derived::show 1
p->show() calls the virtual function show() with no argument. Virtual dispatch selects Derived::show(), but the default argument value is taken from the static type of p, which is Base*. Therefore, the default argument is 1 (from Base::show), not 2.
Line 6: Derived::show 2
d.show() calls Derived::show() directly, using the default argument defined in Derived::show, which is 2.
Line 7: Base::hello
byValue(d) passes the Derived object by value to a function expecting a Base. This triggers object slicing: only the Base portion of d is copied into parameter b. Inside byValue, b is a Base object (not a Derived), so b.hello() calls Base::hello().
Key Language Rules
- Virtual calls during construction: Virtual dispatch does not apply during base-class construction. The dynamic type is not yet the derived class.
- Non-virtual functions and name hiding: Calling a non-virtual function through a base pointer uses the base version, even when pointing to a derived object.
- Default arguments are statically bound: Virtual functions use the default argument from the static type of the pointer or reference, not the dynamic type.
- Object slicing: Passing a derived object by value to a base parameter copies only the base sub-object, losing all derived state and polymorphic behavior.
Avoiding These Pitfalls
- Use
overrideconsistently to catch mistakes (already done here). - Mark classes
finalif they should not be derived from, or mark virtual functionsfinalto stop further overriding. - Avoid calling virtual functions in constructors or destructors.
- Pass polymorphic objects by reference or pointer, never by value.
- Avoid default arguments on virtual functions; prefer overloaded non-virtual wrappers.
- Use modern C++ smart pointers (
std::unique_ptr,std::shared_ptr) to manage ownership and avoid manualdelete.
Summary
Both exercises test precise understanding of language mechanics. Part 1 rewards careful pointer tracing and recognition that every insertion must preserve the existing chain. Part 2 exposes subtleties in virtual dispatch, default arguments, and object slicing that cause surprising behavior if you expect "intuitive" polymorphism everywhere. A strong answer walks through the exact state changes and names the underlying rule for each outcome.