Promises and clean-up
Two problems sink programs written in low-level languages. The first is data that drifts into a nonsensical state: a fraction with a zero denominator, a date on the 31st of April, a bank balance updated by one function that forgot the rule another function relied on. The second is resources that leak: a file opened and never closed because a function returned early, a lock taken and never released because an error was thrown, memory allocated and never freed.
C++ answers both with classes. A class can make its data private and allow changes only through member functions that keep its rules, so a Fraction object is always a valid fraction. And a class can have a destructor, a function the language calls automatically when an object's lifetime ends, whichever way the program leaves the scope. Tie a resource's release to a destructor and you cannot forget it. That second idea, called RAII, is the most important technique in C++, and it is the reason well-written modern C++ contains almost no delete, fclose or unlock calls.
Definitions
Definition— class and struct
A user-defined type grouping data members and member functions. class and struct differ only in their default access: members of a struct are public unless stated otherwise, members of a class private. By convention, struct is used for plain bundles of data with no rules to protect, and class for types with an invariant.
Definition— invariant
A condition that is true of every object of a type whenever code outside the class can see it, for example "the denominator is positive and the fraction is in lowest terms". Constructors establish the invariant; public member functions may break it briefly but must restore it before returning. Private data is what makes an invariant enforceable.
Definition— constructor
A member function with the class's name and no return type, run when an object is created. Its member initialiser list (: num_{num}, den_{den}) initialises the members before the body runs. Members are always initialised in the order they are declared in the class, whatever order the list is written in. A constructor that can be called with one argument also acts as an implicit conversion unless it is marked explicit.
Definition— const member function
A member function declared with const after its parameter list, such as double value() const. It promises not to modify the object, and it is the only kind of member function that can be called on a const object or through a const&.
Definition— destructor
The member function ~ClassName(), called automatically when an object's lifetime ends: at the end of its scope for a local variable, when its owner is destroyed for a member, at the end of the full expression for most temporaries. Objects are destroyed in the reverse order of their construction.
Definition— RAII (resource acquisition is initialisation)
The technique of acquiring a resource in a constructor and releasing it in the destructor, so that the resource's lifetime is exactly the object's lifetime. The name is famously clumsy; some people prefer "scope-bound resource management", which says what it does. std::string, std::vector, std::fstream, std::unique_ptr, std::lock_guard and std::jthread are all RAII types.
A class with an invariant
Here is a Fraction that is always stored in lowest terms with a positive denominator. Because the data is private, no code outside the class can break that promise.
#include <compare>
#include <numeric>
#include <print>
#include <stdexcept>
#include <string>
// A fraction that is always stored in lowest terms with a positive denominator.
// That promise is the class's invariant; every constructor and operation keeps it.
class Fraction {
public:
Fraction(long long num = 0, long long den = 1) : num_{num}, den_{den} {
if (den_ == 0) throw std::invalid_argument("zero denominator");
normalise();
}
long long numerator() const { return num_; }
long long denominator() const { return den_; }
double value() const { return static_cast<double>(num_) / den_; }
std::string str() const {
return den_ == 1 ? std::to_string(num_)
: std::to_string(num_) + "/" + std::to_string(den_);
}
Fraction& operator+=(const Fraction& other) {
num_ = num_ * other.den_ + other.num_ * den_;
den_ *= other.den_;
normalise();
return *this;
}
friend Fraction operator+(Fraction a, const Fraction& b) { return a += b; }
friend bool operator==(const Fraction&, const Fraction&) = default;
friend std::strong_ordering operator<=>(const Fraction& a, const Fraction& b) {
return a.num_ * b.den_ <=> b.num_ * a.den_;
}
private:
void normalise() {
if (den_ < 0) { num_ = -num_; den_ = -den_; }
long long g = std::gcd(num_, den_);
if (g > 1) { num_ /= g; den_ /= g; }
}
long long num_;
long long den_;
};
int main() {
Fraction half{1, 2};
Fraction third{2, -6}; // stored as -1/3
Fraction sum = half + third + 1; // 1 converts to Fraction{1, 1}
std::println("{} {} {}", half.str(), third.str(), sum.str());
std::println("{:.4f}", sum.value());
std::println("{} {}", Fraction{3, 6} == half, third < half);
try {
Fraction broken{1, 0};
} catch (const std::invalid_argument& e) {
std::println("refused: {}", e.what());
}
}1/2 -1/3 7/6
1.1667
true true
refused: zero denominatorThings to notice:
- One constructor with default arguments covers
Fraction{},Fraction{5}andFraction{1, 2}. It refuses a zero denominator by throwing an exception, so an invalidFractionnever exists. (Exceptions get a full lesson later; for now,throwabandons the constructor andcatchhandles the problem.) - The constructor is not
explicit, which is whyhalf + third + 1works:1converts toFraction{1, 1}. That is a deliberate choice for a number-like type. For most classes, mark single-argument constructorsexplicit, so thatMeters m = 5;does not compile by accident. - Accessors are
const. Withoutconstonstr()andvalue(), you could not call them on aconst Fraction&. +=is a member,+is a friend built from it. This is the conventional pattern: the compound operator does the work and returns*thisby reference; the binary operator takes its left operand by value, adds to that copy and returns it. Making+a non-member (afrienddefined inside the class) lets conversions apply to both sides, so1 + halfworks as well ashalf + 1.- Comparisons.
operator==is= default: the compiler compares the members one by one, which is correct because the invariant makes the representation unique (1/2 and 3/6 are stored identically).operator<=>, the C++20 three-way comparison, returns whether one value is less than, equal to or greater than the other, and from it the compiler writes<,<=,>and>=for you. Comparinga/bwithc/dby cross-multiplying is safe here because both denominators are positive.
There is an honest limitation: long long arithmetic can overflow for large numerators, and signed overflow is undefined behaviour. A production rational type would check for it or use arbitrary-precision integers. Knowing where your invariant can still fail is part of designing a class.
Watching objects live and die
Destructors run at precisely defined moments, which is what makes RAII work. This class prints a line when it is created and when it is destroyed:
#include <print>
#include <string>
#include <utility>
class Trace {
public:
explicit Trace(std::string name) : name_{std::move(name)} {
std::println(" construct {}", name_);
}
~Trace() { std::println(" destroy {}", name_); }
private:
std::string name_;
};
struct Pair {
Trace first{"member first"};
Trace second{"member second"};
};
Trace make(const std::string& name) { return Trace{name}; }
int main() {
std::println("start of main");
Trace a{"a"};
{
std::println("enter block");
Trace b{"b"};
Trace c{"c"};
std::println("leave block");
}
std::println("a pair:");
{
Pair p;
}
std::println("returned from a function:");
Trace d = make("d");
std::println("end of main");
}start of main
construct a
enter block
construct b
construct c
leave block
destroy c
destroy b
a pair:
construct member first
construct member second
destroy member second
destroy member first
returned from a function:
construct d
end of main
destroy d
destroy aThe output is completely determined by the rules. Inside the inner block, b is constructed before c, so c is destroyed first: last in, first out, like a stack of plates. A Pair's members are constructed in declaration order and destroyed in reverse. The object returned by make is constructed exactly once, directly in d (guaranteed copy elision again), so you see one construction and one destruction. Finally d and then a are destroyed as main ends.
This determinism is the big difference from garbage-collected languages. A Java finaliser or a Python __del__ runs at some later time chosen by the collector, if at all, so those languages need try-with-resources or with blocks to close files promptly. In C++ the closing brace is the with block.
Analogy, not a formal construction
RAII works like the checkout desk of a library that issues every book with a return slip already filled in and stamped. You cannot borrow a book without the slip existing, and the slip is posted automatically when you leave the building, whichever door you use. Nobody has to remember to return anything.
Wrapping a resource, and the rule of zero
Most resources you will meet already have RAII wrappers in the standard library or in the libraries you use. But C APIs hand you raw handles, and wrapping one is a rite of passage. This program wraps a C FILE* from std::tmpfile(), which creates a temporary file that the system deletes when it is closed.
#include <cstdio>
#include <print>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// RAII: the constructor acquires a C file handle, the destructor releases it.
class TempFile {
public:
TempFile() : f_{std::tmpfile()} {
if (!f_) throw std::runtime_error("could not create a temporary file");
}
~TempFile() {
std::fclose(f_);
std::println("(file closed)");
}
// One object owns one handle, so copying is forbidden (more in the next lesson).
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
void write(const std::string& text) { std::fputs(text.c_str(), f_); }
std::string read_all() {
std::rewind(f_);
std::string out;
for (int ch; (ch = std::fgetc(f_)) != EOF;) out += static_cast<char>(ch);
return out;
}
private:
std::FILE* f_;
};
// The rule of zero: every member already manages itself, so this class
// declares no destructor, no copy and no move operations, and all of them work.
class Logbook {
public:
explicit Logbook(std::string ship) : ship_{std::move(ship)} {}
void add(std::string entry) { entries_.push_back(std::move(entry)); }
std::size_t size() const { return entries_.size(); }
const std::string& ship() const { return ship_; }
private:
std::string ship_;
std::vector<std::string> entries_;
};
int main() {
{
TempFile tmp;
tmp.write("line one\n");
tmp.write("line two\n");
std::print("{}", tmp.read_all());
} // the file is closed here, however we leave the block
Logbook log{"Estrella del Sur"};
log.add("departed Hilo");
Logbook copy = log; // copies the name and every entry
copy.add("sighted land");
std::println("{}: {} and {} entries", log.ship(), log.size(), copy.size());
}line one
line two
(file closed)
Estrella del Sur: 1 and 2 entriesTempFile acquires the handle in its constructor and refuses to exist without one. Its destructor closes it, on every path out of the block, including an exception thrown by write or read_all. And it deletes its copy operations: if two TempFile objects held the same FILE*, both destructors would call fclose on it, and closing a file twice is undefined behaviour. A class that manages a resource by hand has to think about copying, and usually about moving too. That is the rule of three (and, since C++11, the rule of five): if a class needs a hand-written destructor, it almost certainly needs hand-written or deleted copy operations, and should consider move operations. The next lesson covers moves and finishes that story.
Logbook shows the happy alternative, the rule of zero. Its members are a std::string and a std::vector, which already manage their own memory correctly. So Logbook declares no destructor and no copy or move operations at all, and the compiler-generated ones do the right thing: copying a logbook copies the name and every entry, and destroying it frees everything. The C++ Core Guidelines put it simply: if you can avoid defining default operations, do. Most classes in a well-designed codebase follow the rule of zero, and a few small RAII classes (or library types like std::unique_ptr) handle the resources.
Common misconceptions
Misconception
"The member initialiser list sets members in the order I write it." Members are initialised in the order they are declared in the class. If a class declares int hi; int lo; and its constructor says : lo{a}, hi{lo + 10}, then hi is initialised first, from a lo that does not have a value yet. GCC and Clang warn about this with -Wreorder, which -Wall enables. Keep the list in declaration order.
Misconception
"Assigning in the constructor body is the same as using the initialiser list." By the time the body runs, every member has already been initialised. Assigning in the body means initialising twice, and is impossible for const members, reference members and members with no default constructor. Use the list, or default member initialisers like int count_ = 0; in the class body.
Misconception
"Every data member needs a getter and a setter." A setter for every field throws away the invariant: anyone can set a denominator to zero. Offer operations that make sense for the type (add, reduce, deposit) and accessors only for what callers really need. If a type has no invariant at all, make it a struct with public members and skip the boilerplate.
Misconception
"A destructor is like a finaliser in Java or C#." Finalisers run at an unpredictable time, maybe never. A C++ destructor runs at a point you can see in the source code: the closing brace of the scope, or the destruction of the owner. That is why C++ can use destructors for things like releasing locks, where "eventually" would be a bug.
Designing classes the way professionals do
When you design a class, start from its invariant and its operations, not from its data. Ask: what must always be true of a valid object? Which operations does a user need? Which of those can break the invariant, and how will they restore it? The data members are an implementation detail that you should be free to change later without touching any caller.
Keep classes small and give each one a single job. A Fraction does arithmetic on fractions; it does not parse user input or print reports. Code that needs no private access belongs in free functions next to the class, which keeps the class's own surface small. When a class wraps a resource, make the wrapper do only that, and build richer behaviour on top of it with the rule of zero.
Not every type needs a constructor. A plain struct with public members and no constructors is an aggregate, and C++20 lets you initialise one with designated initialisers that name each field: Runner r{.name = "Selam", .seconds = 7799};. The fields must be given in declaration order, and any you leave out take their default member initialisers. For configuration records, options and results, this is often clearer than a constructor with five parameters of similar types.
Finally, let the compiler write what it can: default member initialisers, = default for comparisons and special member functions, and the rule of zero. Code you do not write has no bugs.
Exercises
1. Classes and RAII
Warm-upComputationalWhat does this program print? (It prints no newline, so the answer is one short string.)
#include <print>
struct Noisy {
char c;
~Noisy() { std::print("{}", c); }
};
int main() {
Noisy a{'a'};
{
Noisy b{'b'};
Noisy c{'c'};
}
Noisy d{'d'};
std::print("|");
}
2. Classes and RAII
Warm-upComputationalUsing the lesson's Fraction class, what does this print?
Fraction x = Fraction{4, -8} + Fraction{1, 4};
std::println("{}", x.str());
3. Classes and RAII
CoreHumanA class has the constructor explicit Meters(double value);. Which line does not compile?
4. Classes and RAII
StretchHumanWhat is wrong with this class?
class Window {
public:
explicit Window(int width) : width_{width}, area_{width_ * height_}, height_{width / 2} {}
private:
int width_;
int area_;
int height_;
};
5. Classes and RAII
CoreHumanWhich of these classes need a hand-written destructor (and therefore careful thought about copying)? Select all that apply.
6. Classes and RAII
CoreHumanWhy does the lesson's TempFile declare TempFile(const TempFile&) = delete;?
Further reading and resources
- Classes · cppreference.com
- RAII · cppreference.comA short definition with the standard library's own RAII types listed.
- The rule of three/five/zero · cppreference.com
- Default comparisons (operator== and operator<=>) · cppreference.com
- C++ Core Guidelines: C (classes and class hierarchies) and R (resource management)