1. Problem It Solves
Inheritance models an is-a relationship, virtual dispatch selects derived behavior, a virtual destructor enables safe base-pointer deletion, and override/final check intent. It makes an important constraint visible instead of leaving readers to guess. This lesson keeps only the C++11 core that fits one focused day.
2. Prerequisites
The ideas from Day 26, plus basic variables, functions, and output already introduced.
3. Core Idea
Mental model: Inheritance models an is-a relationship, virtual dispatch selects derived behavior, a virtual destructor enables safe base-pointer deletion, and override/final check intent. Identify the relevant value or state, who owns it, and whether the rule acts during compilation or execution.
4. Minimal Syntax
struct Derived final : Base { const char* name() const override; };5. How It Works
The example creates a tiny fixed state with no keyboard input.
C++11 or the standard-library contract applies today's rule.
The program prints the important result so it can be checked against the source.
6. Common Mistakes
Deleting a derived object through a base pointer whose destructor is not virtual has undefined behavior.
7. When to Use It
Use it when runtime behavior truly varies by subtype and substitution is meaningful.
Avoid it when it hides ownership, lifetime, type, ordering, or cost.
8. Simple Example
A base pointer calls a derived override and then deletes the derived object, showing both destructors execute in the correct order. The .cpp keeps the data fixed and avoids unrelated abstraction.
Complete sample code
Source file
cpp11/27_inheritance_virtual_destructor_override_final/main.cpp
#include <iostream>
class Base {
public:
virtual ~Base() {
std::cout << "Base destroyed\n";
}
virtual const char* name() const {
return "Base";
}
};
class Derived final : public Base {
public:
~Derived() override {
std::cout << "Derived destroyed\n";
}
const char* name() const override {
return "Derived";
}
};
int main() {
Base* object = new Derived;
std::cout << object->name() << '\n';
delete object; // safe because Base has a virtual destructor
}
9. Key Takeaways
The feature is part of the C++11 scope used in this course.
Understand its lifetime, ownership, type, and ordering consequences.
Compile with warnings and prefer the smallest form that makes the rule obvious.
10. Self-Check Questions
Easy — Why does a base class need a virtual destructor when deleting a derived object through a base pointer? What intentions do a function's
overrideand a class'sfinalenforce?Medium — Read the small example described above. What value or state should it print, and which rule produces that result?
Hard — Find and explain the subtle bug in this situation: Deleting a derived object through a base pointer whose destructor is not virtual has undefined behavior. What is the smallest C++11-safe correction?