C++ for Embedded · Interview question

Why does an abstract base class need a virtual destructor?

A strong answer

Because objects are often deleted (or destroyed) through a base-class pointer or reference, IGpio* p = new Stm32Gpio(...); delete p;. If the base destructor isn't virtual, delete p calls only ~IGpio, not ~Stm32Gpio, so the derived part is never properly destroyed, undefined behavior, and any resource the derived destructor would release (a buffer, a clock, a lock) leaks. Declaring virtual ~IGpio() = default; makes destruction dispatch through the vtable to the most-derived destructor, which then chains up the hierarchy correctly. The rule: any class with virtual functions (i.e. intended for polymorphic use) must have a virtual destructor. On embedded you often don't delete (no heap), but the rule still applies to any polymorphic object destroyed through a base reference/pointer, including stack objects in some patterns.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

The HAL Pattern

Abstract a peripheral behind an interface so app logic survives an MCU swap and runs in a PC unit test, using runtime virtuals or zero-overhead compile-time polymorphism.

More The HAL Pattern questions

Browse all 472 interview questions
Why does an abstract base class need a virtual destructor? | EmbeddedPrep.io