Learn++ Lesson 45: The Final Keyword in C++ Programming
The final specifier prevents a virtual function from being overridden in a derived class. This lesson shows how a derived object can still call the inherited implementation.
Mark a method final
#include <iostream>
class Base {
public:
virtual void show() final {
std::cout << "Base class";
}
};
class Derived : public Base {
};
int main() {
Derived derivedObj;
derivedObj.show();
return 0;
}
Output:
Base class
The show method is declared final in Base, so Derived inherits it and cannot override it. Calling show through a Derived object uses the base implementation.
Why final matters
- It protects a method from accidental overrides in a class hierarchy.
- It makes an inheritance contract clear to readers and the compiler.
- It helps preserve stable behavior in derived classes.
What you practice in the app
- Marking a virtual method with
final. - Calling an inherited method from a derived object.
- Recognizing that final blocks overriding but does not block inheritance.
Today's challenge
Fill in the missing method name so the program calls the inherited final method and prints the shown message:
#include <iostream>
class Base {
public:
virtual void show() final {
std::cout << "Base class";
}
};
class Derived : public Base {
};
int main() {
Derived derivedObj;
derivedObj.____();
return 0;
}
The unique intended answer is show, the method defined in Base and inherited by Derived.