Contract assertions on virtual functions
Timur Doumler
Runtime polymorphism is a fundamental part of C++; many libraries and APIs are built around virtual functions. However, the pre and post contract assertions added in C++26 cannot be applied to virtual functions; attempting to do so results in a compiler error. This restriction exists because the ISO C++ committee did not reach consensus, within the C++26 timeframe, on what the semantics of pre and post on virtual functions should be.
Other languages such as Eiffel, D, and Ada have supported contracts on virtual functions for decades, dating back to Bertrand Meyer’s work in the 1980s. While these languages settled on specific semantics (often described as "preconditions can only be widened, postconditions can only be narrowed"), closer analysis shows that parts of this canonical model are incomplete, while others do not carry over to C++ due to differences in object models, compilation strategies, deployment scenarios, dependency management, and the need to mitigate undefined behaviour. A better solution is needed.
In this talk, we systematically explore the design space for supporting contract assertions on virtual functions. We identify the key questions any design must answer, outline the properties a good solution should have, and survey the approaches taken by other languages as well as past C++ proposals. Using this framework, we compare the tradeoffs between different plausible designs. We arrive at a concrete proposal for contract assertions on virtual functions that best balances the competing requirements, which we are pursuing for C++29.
Along the way, we discuss different approaches to API design, the true meaning of the often-misunderstood Liskov substitution principle, how to reason about program correctness, and other topics relevant to a broad range of developers.
Timur Doumler
Timur Doumler is a software engineer specialising in low-latency and real-time C++. He works at Citadel Securities and is an active member of the ISO C++ standard committee, where he has (co-)authored many successful proposals including [[assume]], std::inplace_vector, and contract assertions.
Timur began his C++ journey in computational astrophysics, working on large-scale cosmological simulations. After completing a PhD in astrophysics, he spent a decade in the audio and music technology industry and co-founded the music tech startup Cradle. He has also worked at JetBrains, contributing to their in-house C++ frontend and later serving as Developer Advocate for the CLion IDE and other popular C++ tools.
Timur is passionate about correct code, effective tools, and the evolution of the C++ language.