Click here to Skip to main content
15,436,928 members
Articles / Programming Languages / C++
Posted 15 Sep 2004


34 bookmarked

Design by Contract in C++

Rate me:
Please Sign up or sign in to vote.
4.45/5 (13 votes)
15 Sep 20045 min read
An article decribing how to implement Design by Contact in C++, using lambda expressions.


Every now and then I see attempts at introducing the Design by Contract (DbC) concept into C++, usually using some kind of assertions. There are limits on how well that can work, but I thought that it should be possible to do it better than what I've seen to date.

DbC is usually used to describe three kinds of assertions:

  • Precondition - a condition that must hold upon invocation of a function.
  • Postcondition - a condition that must hold upon exit from a function.
  • Class invariant - a condition that must always hold for objects of the class, except while a public member function is executing.

DbC was introduced to the programming community in the book Object-Oriented Software Construction [1], and is an integrated part of the Eiffel programming language. Few (any?) mainstream languages support it out of the box though, certainly neither C++, C#, nor Java does. Of those three, C++ lends itself the best to the task of implementing DbC, thanks to scope-based object destruction and templates, two features which are lacking in both C# and Java.

The problem

Basically, for a given function, we want to specify a precondition, that needs to hold at the entry into the function, and a postcondition, that needs to hold at the exit of a function, whether by explicit return or by stack unwinding from an uncaught exception. Also, we want to be able to specify a class invariant condition that is checked both at entry and exit from any public member function.

There are limits to what can be done. In particular, it won't be possible to hinder users from overriding virtual functions with implementations that don't fulfill the pre- or postconditions stated in the base function. And the invariant condition cannot be checked automatically; some kind of trigger must be provided by the programmer. None the less, there are a lot of facilities in C++ at our disposal, and we can go quite a distance with them.

The main problem is to specify a postcondition at the beginning of a function, while delaying the actual check until the function is exiting. Destructors of local stack-allocated objects are the key to that problem, together with lambda expressions. We'll also borrow some ideas from [2] to provide useful debugging information for failed conditions. Using the preprocessor, we can put a nice veneer on top of all the machinery. The following example shows what we end up with.


// The Rectangle class represents a rectangular
// viewing area that can be zoomed or translated.
// The rectangle is specified by two corners,
// of which the first must have smaller
// coordinates than the second.

#include "PrePostCondition.h"

namespace Demo {

    class Rectangle
        Rectangle(double x1, double y1, double x2, double y2) :

        double width()
            return x2-x1;

        double height()
            return y2-y1;

        void zoom(double factor)
            PRECONDITION( factor > 0 )(factor);
            POSTCONDITION( POST(width) == 
                width()*factor )(width())(factor)(POST(width));
            POSTCONDITION( POST(height) == 
                height()*factor )(height())(factor)(POST(height));

            // Implementation
            // ...

        void translate(double dx, double dy)
            POSTCONDITION( POST(x1) == x1+dx )(x1)(POST(x1))(dx);
            POSTCONDITION( POST(y1) == y1+dy )(y1)(POST(y1))(dy);
            POSTCONDITION( POST(x2) == x2+dx )(x2)(POST(x2))(dx);
            POSTCONDITION( POST(y2) == y2+dy )(y2)(POST(y2))(dy);

            // Implementation
            // ...


        double x1;
        double y1;
        double x2;
        double y2;

            DEFINE_INVARIANT( x2 > x1 && y2 > y1 )(x1)(x2)(y1)(y2)

} // namespace Demo

int main()
    Demo::Rectangle badRectangle(0,0,-1,-1);
    Demo::Rectangle rectangle(0,0,1,1);
    return 0;

The POST() macro indicates that the argument should not be evaluated until the condition itself is evaluated; without the POST() the argument will be evaluated immediately. The argument can be a variable, free function, or member function.

Both the PRECONDITION and POSTCONDITION macros will check the class invariant, one at entry and the other at exit. When a precondition, postcondition, or invariant fails, the relevant information is printed to the debug output. To see this, compile and run the example code. Since we've neglected to supply implementations for the zoom and translate functions, and on top of that we've had the temerity to create a Rectangle with bad corners, we'll be hit by a slew of failed preconditions, postconditions, and invariants. I would have liked to put a screenshot here of the output window in Visual Studio, showing all the failures, but this article is limited to 600 pixel wide images, and you wouldn't really see anything. In any case, the full text of one of the lines in the output window is:

e:\development\codeproject\designbycontract\demo.cpp(34): FAILURE: 
Postcondition: POST(height) == height()*factor in Demo::Rectangle::zoom: 
Thread-id=2572 : Timestamp(ms)= 35866: height()=1, factor= -1, POST(height)=1,

Here's another one:

e:\development\codeproject\designbycontract\demo.cpp(16): FAILURE: Class 
invariant (on exit): x2 > x1 && y2 > y1 in 
Demo::Rectangle::Rectangle: Thread-id=2572 : 
      Timestamp(ms)=37800: x1=0, x2=-1, y1=0, y2=-1,

Double-clicking these lines will bring you straight to the source code line of the failed condition. Note how easy it is to write out extra variables and values to aid in diagnosing the situation.

The actions to be taken after a failed condition is easily customizable. The default action is to do nothing, i.e. continue with normal execution. A more noticeable action that springs to mind is to trigger an assertion in debug builds, and to throw an exception in release builds. To enable this failure action, redefine the PRECONDITION and POSTCONDITION macros:

#include "PrePostCondition.h" 


#ifdef NDEBUG 
#define PRECONDITION(condition) 
        UTIL_PRECONDITION( util::PrePostCondition::Print_ODS, 
        util::PrePostCondition::Fail_Throw, condition ) 
#define POSTCONDITION(condition) 
        UTIL_POSTCONDITION( util::PrePostCondition::Print_ODS, 
        util::PrePostCondition::Fail_Throw, condition ) 
#define PRECONDITION(condition) 
        UTIL_PRECONDITION( util::PrePostCondition::Print_ODS, 
        util::PrePostCondition::Fail_Assert, condition ) 
#define POSTCONDITION(condition) 
        UTIL_POSTCONDITION( util::PrePostCondition::Print_ODS, 
        util::PrePostCondition::Fail_Assert, condition ) 

If a condition failure is detected during a stack unwind from an uncaught exception, then no action is taken; throwing another exception in such cases would unceremoniously terminate the whole program.

Implementation details

We use destructors of local variables to delay the checking of postconditions and invariants. In order to store the expressions constituting the condition, we make use of the Boost Lambda Library [3], which allows us to build complex expressions that can be stored and evaluated at some latter point in time. To allow users to output extra information when a condition fails, we apply some preprocessor magic from [2], creating what in effect is a variable argument macro.

Because of the heavy use of lambda expressions, there is a noticeable increase in compilation time when using these macros. I haven't tried to optimize the framework with respect to compile-time; currently there is an abundance of functors and compile-time lambda expressions, obviating a number of these would definitely help the compilation time. Using precompiled headers and instantiating common templates there also helps.

The runtime penalty is also significant, especially in debug builds since no inlining is performed. This is generally less of an issue though. While testing a program, we can put up with a performance loss to help localize DbC violations, and once a program is determined to be running correctly, the checking can be disabled.

The included sample program has been compiled and tested with Visual C++ 7.1. It almost surely won't work with earlier versions of Visual C++, due to compiler idiosyncrasies (a.k.a. bugs). The Boost Function and Lambda libraries are required, and may be downloaded as part of the Boost library [4]. I've tested against versions 1.30 and 1.31 of Boost.


I've presented a C++ framework for implementing DbC, which allows class invariants, preconditions, and postconditions to be stated up front and enforced at the correct times, with extensive diagnostic information when a failure is encountered.

Comments are gratefully received. If you come across some bugs, please tell me!


[1] - Bertrand Meyer: Object-Oriented Software Construction, Second Edition, Prentice Hall, 1997.

[2] - Andrei Alexandrescu, John Torjo: Enhancing Assertions, C++ Users Journal, August 2003.

[3] - Jaakko Järvi, Gary Powell: Boost Lambda Library.

[4] -


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Written By
Australia Australia
Software developer, ex-resident of Sweden and now living in Canberra, Australia, working on distributed C++ applications. Jarl enjoys programming, but prefers skiing and playing table tennis. He derives immense satisfaction from referring to himself in third person.

Comments and Discussions

GeneralI like this Pin
Dave Abrahams12-Jan-12 1:34
MemberDave Abrahams12-Jan-12 1:34 
GeneralBut it doesn't build with GCC :( Pin
Dave Abrahams12-Jan-12 14:11
MemberDave Abrahams12-Jan-12 14:11 
QuestionTrying to use this code Pin
Thomas Wicklund28-Sep-11 6:34
MemberThomas Wicklund28-Sep-11 6:34 
AnswerRe: Trying to use this code Pin
Jarl Lindrud28-Sep-11 20:19
MemberJarl Lindrud28-Sep-11 20:19 
GeneralRe: Trying to use this code Pin
Thomas Wicklund29-Sep-11 5:08
MemberThomas Wicklund29-Sep-11 5:08 
GeneralRe: Trying to use this code Pin
Thomas Wicklund2-Oct-11 16:13
MemberThomas Wicklund2-Oct-11 16:13 
GeneralNice, but I prefer ModAssert Pin
JasonReese17-May-06 23:55
MemberJasonReese17-May-06 23:55 
GeneralPreconditions Pin
dilas26-Sep-04 2:11
Memberdilas26-Sep-04 2:11 
GeneralRe: Preconditions Pin
Jarl Lindrud28-Sep-04 1:32
MemberJarl Lindrud28-Sep-04 1:32 
GeneralRe: Preconditions Pin
dilas30-Sep-04 4:22
Memberdilas30-Sep-04 4:22 
GeneralRe: Preconditions Pin
dosler23-Aug-05 2:54
Memberdosler23-Aug-05 2:54 
GeneralMy C++ DbC Framework Pin
Kevin McFarlane24-Sep-04 9:41
MemberKevin McFarlane24-Sep-04 9:41 
GeneralRe: My C++ DbC Framework Pin
Jarl Lindrud24-Sep-04 11:14
MemberJarl Lindrud24-Sep-04 11:14 
GeneralRe: My C++ DbC Framework Pin
Kevin McFarlane24-Sep-04 12:24
MemberKevin McFarlane24-Sep-04 12:24 
GeneralGreat Pin
waiting_for_you15-Sep-04 16:12
Memberwaiting_for_you15-Sep-04 16:12 
QuestionHave you looked at Digital Mars C++? Pin
Don Clugston15-Sep-04 13:43
MemberDon Clugston15-Sep-04 13:43 
AnswerRe: Have you looked at Digital Mars C++? Pin
Jarl Lindrud16-Sep-04 7:09
MemberJarl Lindrud16-Sep-04 7:09 
GeneralRe: Have you looked at Digital Mars C++? Pin
Don Clugston16-Sep-04 13:42
MemberDon Clugston16-Sep-04 13:42 
GeneralConfused and Confusing Pin
Code Inspector15-Sep-04 9:23
sussCode Inspector15-Sep-04 9:23 
GeneralRe: Confused and Confusing Pin
Jarl Lindrud15-Sep-04 10:34
MemberJarl Lindrud15-Sep-04 10:34 
GeneralRe: Confused and Confusing Pin
Neville Franks17-Sep-04 22:40
MemberNeville Franks17-Sep-04 22:40 
Generaluse, but don't abuse ! Pin
Emilio Garavaglia15-Sep-04 3:51
MemberEmilio Garavaglia15-Sep-04 3:51 
GeneralRe: use, but don't abuse ! Pin
Jarl Lindrud18-Sep-04 1:41
MemberJarl Lindrud18-Sep-04 1:41 
GeneralGreat! Pin
Nemanja Trifunovic15-Sep-04 2:06
MemberNemanja Trifunovic15-Sep-04 2:06 
GeneralRe: Great! Pin
Jarl Lindrud15-Sep-04 3:53
MemberJarl Lindrud15-Sep-04 3:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.