C++ Memory Semantics, Dynamic Dispatch, and Override Pitfalls
System DesignModel answerLast updated
Explain pointers vs references, vtable-based dispatch internals, and the override specifier, then diagnose three bugs in a polymorphic sensor class hierarchy.
Context
Embedded and real-time systems — robotics controllers, sensor fusion pipelines, medical devices — rely on C++ precisely because it gives you deterministic memory layout and zero-cost abstractions. But that power cuts both ways: a wrong const qualifier, a missing virtual, or a by-value parameter can silently corrupt behavior in ways that are hard to reproduce under a debugger.
This problem asks you to reason from first principles about three interconnected mechanisms, then apply that reasoning to find and fix concrete bugs.
Part 1: Conceptual Questions
Answer each of the following in a few focused paragraphs. Depth and precision matter more than length.
1. Pointers vs. References Compare the two on: syntax, memory representation, nullability, the ability to rebind, and the lifetime hazards unique to each. When would you reach for one over the other in a modern codebase?
2. Runtime Polymorphism Internals How does the compiler actually implement a virtual function call? Describe the roles of the vtable and the vptr, where each lives in memory, how they are initialized, and what the runtime cost of a virtual call looks like — both the direct cost and the indirect (optimization-blocking) cost.
3. The override Specifier
What gap in C++03 did override close? Describe exactly which parts of a function signature must match for an override to be valid, and explain what happens — at both compile time and runtime — when the specifier is omitted and a signature mismatch goes undetected.
Part 2: Code Diagnosis
The following snippet models a sensor abstraction for a robotics platform. It compiles without warnings on many configurations, yet it contains three critical bugs or architectural flaws. Identify each one, explain the observable consequence (including what happens to heap memory), and provide a corrected version of the classes.
#include
#include
class Sensor {
public:
Sensor() = default;
~Sensor() {
std::cout << "Sensor destroyed\n";
}
virtual void configure() {
std::cout << "Default sensor configuration\n";
}
virtual void processData(const double& timestamp) {
std::cout << "Base processing at " << timestamp << "\n";
}
};
class CameraSensor : public Sensor {
private:
int* rawFrameBuffer;
public:
CameraSensor() : rawFrameBuffer(new int[1024]) {}
~CameraSensor() {
delete[] rawFrameBuffer;
std::cout << "CameraSensor buffer freed\n";
}
// Intended to override base configure
void configure() const {
std::cout << "Camera customized configuration\n";
}
// Intended to override base processData
void processData(double& timestamp) {
std::cout << "Camera processing at " << timestamp << "\n";
}
};
void runDiagnostics(Sensor s) {
s.configure();
}
For your analysis, address:
- What does
runDiagnosticsactually do when handed aCameraSensorinstance, and why? - What happens to heap memory when a
CameraSensorowned by astd::unique_ptr<Sensor>goes out of scope? - How would adding
overrideto theCameraSensormethods change the compilation outcome?
Your answer should include a corrected, compiling version of both classes.
Hints
Hint 1
For the conceptual comparison, think about what the compiler is *required* to store in memory for each. A reference and a pointer often lower to the same machine representation, but the language rules around them are very different — focus on those rules rather than the assembly.
Hint 2
For the vtable question, trace what happens between the moment you write `new CameraSensor()` and the moment a virtual call resolves. Which constructor runs first? When exactly does the vptr get set, and to which table?
Hint 3
When hunting the three bugs, check the destructor, then check each method signature character by character against its base declaration — name, parameter types, and cv-qualifiers on `this`. Finally, look at how the base class is passed into `runDiagnostics` and think about what the copy constructor does with a derived object.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
The interviewer is probing two things simultaneously: do you have a precise mental model of how C++ lays out objects and dispatches calls, and can you translate that model into bug recognition? Both halves matter. A generic explanation of polymorphism without catching the slicing bug, or catching the bugs without being able to explain why they happen, is a partial answer.
Part 1: Conceptual Answers
Pointers vs. References
A pointer is an object in its own right. It occupies storage (8 bytes on a 64-bit platform), can be null, can be reassigned to point elsewhere, supports arithmetic within an array, and can be tested for validity. A reference is an alias for an existing object — the language guarantees it cannot be null and cannot be rebound after initialization. sizeof(r) reflects the size of the referent, not a pointer-sized slot.
Under the hood, the compiler usually implements a reference as an address, so the generated machine code is often identical. The difference is entirely in what the language permits.
Both can dangle, but in different ways. A dangling pointer is at least detectable — you can null it out after delete and check before use. A dangling reference is more treacherous because the code reads as if the object is alive: returning a T& to a local, binding to a container element that later reallocates, or passing a temporary into a const T& parameter that outlives the call site. One subtle rule: a const T& bound directly to a temporary extends that temporary's lifetime to match the reference. A const T& returned from a function that bound a temporary internally does not extend it — the temporary is already gone.
Practical guidance: use references for non-null, non-owning parameters and return values. Use raw pointers for optional, non-owning access where null is meaningful. Use unique_ptr or shared_ptr for ownership.
Runtime Polymorphism Internals
Most compilers (Itanium ABI, MSVC) implement virtual dispatch with two structures:
vtable — one per polymorphic class, allocated statically in read-only data. It is an array of function pointers, laid out in declaration order. A derived class starts with a copy of its base's vtable and replaces the slots it overrides. The table also holds RTTI metadata and, for multiple inheritance, "thunks" that adjust this before calling an overrider.
vptr — one per object instance, typically at offset zero. It is a pointer to the class's vtable. Each constructor in the chain writes its own class's vtable address into the vptr, which is why virtual calls inside a constructor resolve to the currently-constructing type, not the final derived type.
On a 64-bit system, the vptr adds 8 bytes to every instance. Multiple inheritance can add more.
A call sensor->configure() compiles to roughly: load vptr from *sensor, load the function pointer at the correct slot offset, indirect-call it. That is two dependent loads plus an indirect branch — inexpensive in isolation, but the indirect branch is usually unpredictable enough to block the compiler from inlining, which in turn blocks constant propagation, loop vectorization, and other optimizations. This is the larger cost. The compiler can eliminate the dispatch ("devirtualize") when the dynamic type is statically provable — final classes, profile-guided optimization, or a local variable of known concrete type.
The override Specifier
In C++03, a derived function overrides a base virtual only if the full signature matches: name, parameter types (after decay), const/volatile qualifiers on this, and ref-qualifiers. Covariant return types are the sole permitted relaxation. Any mismatch silently introduced a new, unrelated function that hid the base one rather than replacing it. No diagnostic was required, and many compilers issued none by default.
override makes the intent explicit and turns a mismatch into a hard compile error. final additionally forbids further overriding in subclasses, which also lets the optimizer devirtualize calls through that type. Without override, calls through a base pointer or reference invoke the base implementation regardless of what the derived class declares — silent wrong behavior, not a crash, which makes it difficult to catch in testing.
Part 2: Bug Diagnosis
Bug 1 — Non-virtual destructor (critical, causes memory leak and UB)
~Sensor() is not virtual. When a CameraSensor is owned as std::unique_ptr<Sensor>, the smart pointer calls delete on a Sensor*. Because the destructor is non-virtual, the call resolves statically to ~Sensor, skipping ~CameraSensor entirely. The delete[] rawFrameBuffer line never runs: 4 KB leaked per instance, and the behavior is formally undefined.
Note: std::shared_ptr<Sensor> created from a CameraSensor* would be safe by accident, because shared_ptr captures a type-erased deleter at construction time. unique_ptr does not — it deletes through the stored pointer type.
Fix: virtual ~Sensor() = default;
Bug 2 — Signature mismatches hide instead of override (logic bug, silent)
CameraSensor::configure() is declared const, while the base is non-const. These are different signatures; the const qualifier is part of the implicit this parameter. The derived method introduces a new, non-virtual function and the base slot is untouched.
CameraSensor::processData(double&) takes a non-const lvalue reference, while the base takes const double&. Again a different signature — and as a bonus, the derived version cannot bind to an rvalue like sensor.processData(3.14).
The result: any call through a Sensor* or Sensor& runs the base implementations. The code compiles cleanly and the bug is invisible without override.
Adding override to either declaration produces an immediate compile error ("function does not override any base class virtual function"), forcing the signatures to be corrected.
Bug 3 — Object slicing in runDiagnostics (architectural flaw)
runDiagnostics(Sensor s) takes its argument by value. Passing a CameraSensor invokes Sensor's copy constructor, which copies only the Sensor subobject. The derived portion — including the vptr pointing to CameraSensor's vtable — is sliced away. Inside the function, s is a plain Sensor; s.configure() always calls the base version regardless of what was passed in.
Fix: take the parameter by reference — Sensor& or const Sensor&. To make slicing impossible at the class level, delete the base copy constructor and copy-assignment operator.
Bonus flaw — Rule of Zero violation: CameraSensor owns a raw new[] allocation but relies on implicitly generated copy operations. A copy would duplicate the pointer, and both destructors would delete[] the same buffer — double-free, undefined behavior. Replace the raw pointer with std::vector<int> or std::unique_ptr<int[]> and the problem disappears without writing any destructor logic.
Corrected Code
#include <iostream>
#include <memory>
#include <vector>
class Sensor {
public:
Sensor() = default;
virtual ~Sensor() = default;
// Delete copy operations to make slicing a compile error.
Sensor(const Sensor&) = delete;
Sensor& operator=(const Sensor&) = delete;
virtual void configure() {
std::cout << "Default sensor configuration\n";
}
// Scalars are cheaper passed by value than by const-ref.
virtual void processData(double timestamp) {
std::cout << "Base processing at " << timestamp << "\n";
}
};
class CameraSensor final : public Sensor {
public:
CameraSensor() : rawFrameBuffer_(1024) {}
// vector cleans up automatically; no explicit destructor needed.
void configure() override {
std::cout << "Camera customized configuration\n";
}
void processData(double timestamp) override {
std::cout << "Camera processing at " << timestamp << "\n";
}
private:
std::vector<int> rawFrameBuffer_; // Rule of Zero: no leaks, no double-free
};
// Reference parameter: no slicing, no unnecessary copy.
void runDiagnostics(Sensor& s) {
s.configure();
}
int main() {
std::unique_ptr<Sensor> cam = std::make_unique<CameraSensor>();
runDiagnostics(*cam); // prints "Camera customized configuration"
// ~CameraSensor runs correctly when cam goes out of scope
}
Common mistakes to avoid
- Assuming
shared_ptr<Base>is always safe for polymorphic deletion — it is, but only because of the captured deleter.unique_ptr<Base>is not safe without a virtual destructor. - Thinking
overridechanges runtime behavior — it is purely a compile-time check. - Forgetting that
conston a member function is part of the signature. Adding or removing it creates a new overload, not an override. - Passing polymorphic base classes by value anywhere in a call chain.