Class Invariants in C++

Class invariants is consistency checks that is written as a method. That method is called when every normal entrance and exit from the function. Let’s write class invariants simply. This page which my site introduces every time shows the following code:

class A {
public:
#ifdef DBG
virtual void invariant() { …contracts… }
#endif
void foo();
};

You should write a code that call invariant at inside of the function.

void A::foo() {
#ifdef DBG
invariant();
#endif

#ifdef DBG
invariant();
#endif
}

This page recommends that you use a template to include macro lines. That’s smart means.

template
inline void check_invariant
(T& iX)
{
#ifdef DBC
iX.invariant();
#endif
}

void A::foo()
{
check_invariant(*this);

check_invariant(*this);
}

A simple invariant can be realized in this way. But, you must work so much to achieve DbC completely because DbC of D programming language is more excellent.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s