parts/6.42.ViolationsOfTheLiskovSubstitutionPrincipleOrTheContractModel-BLP.md

6.42 Violations of the Liskov Substitution Principle or the Contract Model [BLP]

6.42.1 Applicability to language

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;
         }
     // ...      
 };

6.42.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can:

See also C++ Core Guidelines C.120, C.121, C.122, C.126, C.127, and C.129 through C.133.