Explain C++ virtual dispatch and object lifetime
J.P. MorganData Scientist · OnsiteLast updated
This question tests the candidate's understanding of C++ memory management, the mechanics of the virtual method table (vtable), and the importance of virtual destructors in polymorphic inheritance.
The Problem
You are working on a high-performance quantitative trading library where object lifetime and memory safety are critical. Analyze the following C++ code snippet and answer the questions provided below.
class Base {
public:
Base() { std::cout << "Base Ctor"; }
~Base() { std::cout << "Base Dtor"; }
virtual void process() { std::cout << "Base Process"; }
};
class Derived : public Base {
public:
Derived() { std::cout process();
delete ptr;
}
Your Tasks:
- Virtual Dispatch: Explain how
ptr->process()callsDerived::process()even though the pointer type isBase*. - Memory Safety: Describe the issue with the code above regarding object destruction. What will happen when
delete ptris called, and how do you fix it? - Lifetime: Briefly explain the difference in lifetime and management between creating an object on the stack (
Derived d;) versus the heap (new Derived();).
Hints
Hint 1
Consider how the compiler uses a hidden pointer (often called a vptr) inside an object to resolve virtual functions at runtime.
Hint 2
Think about what the compiler generates for a non-virtual destructor when the object is deleted through a base class pointer.
Hint 3
Contrast the automatic scope-based cleanup of stack variables with the manual memory management required for heap-allocated pointers.
Follow-up questions
- How do smart pointers like std::unique_ptr or std::shared_ptr mitigate the risk of memory leaks in this specific example?
- What are the performance trade-offs associated with using virtual functions in a latency-sensitive application?
- How does the behavior of the code change if we pass the object by value (`void func(Base b)`) instead of using a pointer or reference?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.