The vulnerability as documented in ISO/IEC 24772-1 clause 6.42 applies to C++. C++ leaves verification of the correctness of an overridden call to the programmer.
The vulnerability can be mitigated by a style of programming that uses wrapper functions to check preconditions, calls a virtual function to perform the required functionality and subsequently checks the postconditions before returning. An example is provided below.
class Base {
private:
virtual int function_to_override( int x ) = 0;
// ...
public:
int interface_to_overridden_function( int x ) {
check_preconditions( x );const auto saved = data_saved_for_postcondition( x );
auto result = function_to_override( x );
check_postconditions( x, saved, result );return result;
}// ...
};
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Obey all preconditions and postconditions of each member function, whether they are specified in the language or not.
Prohibit the strengthening of preconditions (specified or not) by overriding member functions.
Prohibit the weakening of postconditions (specified or not) by overriding member functions.
Prohibit the use of public inheritance for “has-a” relationships. Use composition for “has-a”-relationships instead.
Use static analysis tools that identify misuse of inheritance in the contract model.
Ensure that all invariants of a derived class are preserved by all public operations on its public base classes, and if this cannot be ensured, make the base class private, or avoid inheritance.
See also C++ Core Guidelines C.120, C.121, C.122, C.126, C.127, and C.129 through C.133.