What does final mean on a virtual function versus a class, and when is it appropriate?
Show answer and explanation
On a virtual member function, final prevents any further-derived class from overriding that function; it can mark either a newly introduced virtual or one that already overrides a base virtual, so unlike override it does not require a prior base declaration. On a class definition, final prevents the class from being used as a base. Both constraints let the compiler diagnose unsupported extension and may expose devirtualization opportunities, but they promise no particular performance improvement. Use final when the semantic contract, invariant, security boundary, or closed hierarchy genuinely forbids extension; applying it everywhere can make testing and later evolution unnecessarily rigid.
On a virtual member function, final prevents any further-derived class from overriding that function; it can mark either a newly introduced virtual or one that already overrides a base virtual, so unlike override it does not require a prior base declaration. On a class definition, final prevents the class from being used as a base. Both constraints let the compiler diagnose unsupported extension and may expose devirtualization opportunities, but they promise no particular performance improvement. Use final when the semantic contract, invariant, security boundary, or closed hierarchy genuinely forbids extension; applying it everywhere can make testing and later evolution unnecessarily rigid.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.