← Previous · All Episodes · Next →
Unpacking the C++ Final Specifier Cautionary Tales in Inheritance and Testing Episode

Unpacking the C++ Final Specifier Cautionary Tales in Inheritance and Testing

· 02:17

|

Welcome back, tech thinkers! Today, we’re digging into a tiny but surprisingly prickly piece of the C++ world — the final specifier. It might sound like a power move, locking down your classes and functions from further tampering, but as Sandor Dargo points out in his recent blog post, it’s a tool best used with caution — or maybe not at all. Although final serves to prevent inheritance or overrides, it often hinders flexibility more than it helps performance, and can create real headaches in testing scenarios, especially with mocking frameworks like Google Mock. As Sandor warns, “Don’t mark your mocks final — unless you’re planning a career in debugging cryptic compile-time errors.” Let’s break this nuanced advice down.

Key Takeaways:

  • What is final in C++:

    • final is a specifier (not a keyword!) that prevents future derivation or overriding.
    • It can be applied to classes (to prevent inheritance) or virtual functions (to prevent overrides).
    • Example: class Derived final : public Base {}; — no other class can inherit from Derived.
  • Be cautious when using final:

    • The C++ Core Guidelines recommend using final sparingly (see rules C.139 and C.128).
    • It can block extensibility in class hierarchies.
    • Contradicting popular belief, it rarely brings performance benefits — "measure first" is the mantra.
  • Use in functions:

    • When used, final should be one of virtual, override, or final — but never more than one.
    • final denotes that a virtual function is not to be overridden further down the inheritance chain.
  • Problems with mocks:

    • In testing, especially with Google Mock (gmock), marking a mock class as final blocks inheritance by NiceMock and StrictMock, which use CRTP (Curiously Recurring Template Pattern).
    • This results in compilation failures if your mock class is final.
  • Pro tip:

    • If you're using gmock: avoid final on your mock classes.
    • Mocking tools like NiceMock and StrictMock need to inherit from your class to work.
  • Most suggested mocking tools in this context:

    • Google Mock (gmock)
    • NiceMock, StrictMock for controlling test behavior

Final thoughts (pun intended): Use the final specifier only when absolutely necessary. It’s not your performance fairy godmother, and it can wreak havoc in testing environments. Sometimes putting up walls just makes it harder to build.

For the full article and more of Sandor’s insightful C++ commentary, head over to sandordargo.com.
Link to Article


Subscribe

Listen to jawbreaker.io using one of many popular podcasting apps or directories.

Apple Podcasts Spotify Overcast Pocket Casts Amazon Music
← Previous · All Episodes · Next →