Class Invariants -- Andrzej Krzemieński

Andrzej-Krzemieński.pngThis article explores the concept of class invariants in C++ and their significance in maintaining code integrity and abstraction. It highlights the difference between struct and class definitions and discusses the role of class invariants in guaranteeing the correctness of class objects. The article also touches upon the trade-offs between strong and weak invariants and provides insights into when to define a new class with proper invariants.

Class Invariants

by Andrzej Krzemieński

From the article:

The primary motivation for defining a class in C++ is to reflect and maintain a class invariant. In this post we will see what class invariants are and how you deal with them. Class invariants are important part of C++, even though there is no “invariant” keyword in C++.

Contrast the following two class definitions:

struct Point
{
  int x;
  int y;
};
class Range
{
  int _min;
  int _max;

public:
  // ...
};

In C++ a struct is practically a class but with a different default member access. The first is an aggregate: it only allows two pieces of data to travel together. If it was not for the nice member names, we might have as well used std::pair<int, int> instead. 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.