Katkat

Compare C++ Virtual Dispatch with CRTP

Hudson River TradingSoftware Engineer · Onsite

Last updated

Compare C++ virtual dispatch with CRTP across runtime flexibility, object layout, separate compilation, heterogeneous collections, inlining, code size, diagnostics, ABI stability, and measured performance.

Explain how C++ virtual functions are commonly implemented and compare runtime polymorphism with the Curiously Recurring Template Pattern. Discuss object layout, dispatch, extensibility, code generation, and when each design is appropriate.

Constraints & Assumptions

  • The C++ standard specifies behavior but not one mandatory vtable layout.
  • The comparison should include separate compilation and heterogeneous collections.
  • Do not claim that one indirect call is always a meaningful performance problem.

Clarifying Questions to Ask

  • Must implementations be selected at runtime or are concrete types known at compile time?
  • Will objects be handled through one stable ABI across shared-library boundaries?
  • Is binary size or build time a material constraint?

Follow-up questions

  • How can devirtualization remove the indirect call?
  • Can CRTP store unrelated derived objects in one container without another abstraction?
  • When would type erasure be a better compromise?