Skip to content

Classes, objects, and access control

Difficulty: Beginner

Key concepts

  • class
  • object
  • member function
  • public
  • private
  • protected
  • struct
  • invariant
  • encapsulation
  • What a class and an object are, and how member functions work on an object’s data.
  • How public and private let a class keep its own rules true.
  • What protected means, and why it rarely suits data.
  • When a plain struct with public members is the right choice.
  • Why adding a getter and a setter for every field does not protect anything.

A class describes a kind of thing: the data each one holds and the operations it supports. An object is one particular thing of that kind, with its own copy of the data. Book is a class; “the library’s copy of Design Patterns” is an object of that class.

The data inside a class are its data members (often called fields). The functions declared inside a class are its member functions. A member function is called on a particular object, book.lend_copy(), and works on that object’s data.

Why does this matter for design? Because a class decides which operations exist. If the only way to change a book’s loan count is lend_copy(), then lend_copy() is the only place that can break the rule about loans, and the only place you need to check.

A library lends copies of books. One rule matters: copies on loan can never exceed the copies the library owns, and neither number can be negative. Here is the first design most people write:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

public_book.cpp
// A book as three loose fields. `struct` means every member is public: any
// code that can see a Book can read or overwrite any of the three. The
// rule "0 <= copies_on_loan <= copies_total" exists only in people's heads;
// nothing in the type mentions it, so nothing enforces it.
struct Book {
std::string title;
int copies_total = 0; // "= 0" gives a starting value if none is given
int copies_on_loan = 0;
};
// Lends one copy of `book`. `Book&` is a reference: the function works on
// the caller's own Book, not a copy, so the change is seen by the caller.
// Every caller must remember the rule. This one forgot: it never checks
// that a copy is free, so it happily counts a loan of a copy that is not
// on the shelf. The bug is here, but the struct is what lets it happen.
void lend_copy(Book& book) {
++book.copies_on_loan; // adds 1 whether or not a copy is available
}

struct Book has three public data members, and a free function lends a copy. It compiles and looks reasonable. But every piece of code that touches a Book can change any field to any value, so the rule holds only if every caller remembers it. This caller forgot to check for a free copy:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

public_book.cpp
// The braces fill the fields in order: title "Design Patterns",
// copies_total 2, copies_on_loan 0. So far the book is valid.
Book book{"Design Patterns", 2, 0};
lend_copy(book); // 1 on loan of 2: still fine
lend_copy(book); // 2 on loan of 2: every copy is out
lend_copy(book); // a third loan of a two-copy book: 3 of 2, rule broken
book.copies_total = -1; // nothing prevents this either: a public field takes any int
// Now the book claims 3 copies on loan out of -1. Nothing crashed and
// nothing complained; the wrong numbers just sit there until some later
// code (a report, a stock check) trips over them.

After these lines the book has three copies on loan out of a total of -1. The program does not crash; it is just wrong, and the error is discovered later, somewhere else, when a report shows impossible numbers. In a large program, the code that broke the rule and the code that notices might be in different files written by different people.

The fault is not one careless line. The design gives the rule no owner: any code can change the fields, so any code can be the one that breaks the rule.

The improved design: the class keeps its own rule

Section titled “The improved design: the class keeps its own rule”

The fix is to make the rule the class’s job. A rule that must always hold for an object is called an invariant. The improved Book keeps its data private and offers a small public interface whose operations keep the invariant true:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

book.hpp
// One book in the library's stock: its details, how many copies the
// library owns, and how many are out on loan. The class's job is to keep
// the numbers sensible, which it can do because the numbers are private
// and the only way to change them is through lend_copy and return_copy.
//
// Invariant (a rule that is true for every Book, at every moment a caller
// can see it): the title is not empty, copies_total_ >= 1, and
// 0 <= copies_on_loan_ <= copies_total_.
class Book {
public:
// Everything under `public:` is the interface: what other code may call.
//
// The constructor builds a Book from its details and its number of
// copies, with nothing on loan yet. Throws std::invalid_argument if the
// title is empty or copies < 1, so a Book that breaks the invariant is
// never created. `details` is taken by value and moved into the Book
// (see book.cpp).
Book(BookDetails details, int copies);
// Read-only accessors. `const std::string&` hands back a reference to
// the Book's own string, so nothing is copied, and `const` stops the
// caller from changing it through that reference. The `const` after
// the brackets promises the call does not change the Book; noexcept
// promises it never throws; [[nodiscard]] warns if the result is
// ignored (see the idiom reference in "Reading the examples").
[[nodiscard]] const std::string& isbn() const noexcept { return details_.isbn; }
[[nodiscard]] const std::string& title() const noexcept { return details_.title; }
[[nodiscard]] int copies_total() const noexcept { return copies_total_; }
// Worked out when asked, not stored: total minus on loan. Storing it
// too would add a second rule (the numbers must add up) to keep true.
[[nodiscard]] int copies_available() const noexcept {
return copies_total_ - copies_on_loan_;
}
// The only two ways to change the loan count. Each checks the
// invariant before touching anything, so a refused call leaves the
// Book exactly as it was.
// Lends one copy. Returns false, and changes nothing, if none is available.
bool lend_copy();
// Takes one copy back. Returns false, and changes nothing, if none is on loan.
bool return_copy();
private:
// Everything under `private:` can be named only inside Book's own
// member functions. Outside code that writes book.copies_on_loan_
// does not compile, so no caller can break the invariant.
BookDetails details_;
int copies_total_; // set by the constructor, never changed afterwards
int copies_on_loan_ = 0; // "= 0": every new Book starts with nothing on loan
};

Read it from the top:

  • The invariant is written down in a comment, so a reader knows what the class promises. It adds two rules to the loan rule from the problem: a book has a title and at least one copy.
  • The constructor creates a Book and checks the starting values. If they break the invariant, it throws an exception, so a Book that breaks the rule can never exist. (Constructors are covered fully in the next lesson.)
  • The accessors (isbn, title, copies_total, copies_available) let callers read the state but not change it. The const after the parameter list promises that calling them does not modify the object; [[nodiscard]] asks the compiler to warn if the result is ignored.
  • The operations lend_copy and return_copy are the only ways to change the loan count. Each one checks the rule first and reports whether it did anything.
  • The data members are private, so code outside the class cannot name them. The compiler rejects book.copies_on_loan_ = 7; with an error.

The class stores copies_on_loan_, not copies_available_, and computes availability when asked. Storing both would create a second rule (the two must add up to the total) that every operation must maintain. Storing less is often the simplest way to keep an invariant.

The member function bodies are in book.cpp:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

book.cpp
// `Book::` says these are Book's member functions, declared in book.hpp.
//
// The constructor. The part after the colon is the member initializer
// list: it gives each member its starting value before the body runs.
// `details` is the constructor's own object (it was passed by value), so
// std::move hands its strings over to details_ instead of copying them
// again; `details` is not used afterwards. copies_on_loan_ is not listed,
// so it takes its default of 0 from the class. The body then checks the
// invariant. If a check fails, `throw` leaves the constructor with an
// exception, and an object whose constructor throws is never created:
// the caller gets no Book at all, never a broken one.
Book::Book(BookDetails details, int copies)
: details_(std::move(details)), copies_total_(copies) {
if (details_.title.empty()) throw std::invalid_argument("a book needs a title");
if (copies_total_ < 1) throw std::invalid_argument("a book needs at least one copy");
}
// Check first, then change. If every copy is already out, `return false`
// leaves at once and the count is untouched. Otherwise one more copy goes
// out, and copies_on_loan_ is still at most copies_total_.
bool Book::lend_copy() {
if (copies_on_loan_ == copies_total_) return false;
++copies_on_loan_;
return true;
}
// The mirror image: refuse when nothing is on loan, so the count can
// never go below 0.
bool Book::return_copy() {
if (copies_on_loan_ == 0) return false;
--copies_on_loan_;
return true;
}

Each operation either succeeds or changes nothing. A caller who tries to lend a copy that does not exist gets false, and the book is still valid. Here is the class in use:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The inner braces build the BookDetails (isbn, then title); 2 is the
// number of copies. print_status (above main) prints "N of M available".
Book book({"978-0201633610", "Design Patterns"}, 2);
std::cout << book.title() << '\n';
print_status(book); // 2 of 2 available
// lend_copy returns a bool; std::boolalpha (set above) prints it as
// true or false instead of 1 or 0.
std::cout << "lend: " << book.lend_copy() << '\n'; // true: 1 on loan
std::cout << "lend: " << book.lend_copy() << '\n'; // true: 2 on loan
std::cout << "lend: " << book.lend_copy() << '\n'; // no copy left: false, nothing changes
print_status(book); // 0 of 2 available
std::cout << "return: " << book.return_copy() << '\n'; // true: 1 on loan
print_status(book); // 1 of 2 available
// An empty title breaks the invariant, so the constructor throws.
// `try` runs the code inside it; if anything there throws a
// std::invalid_argument, control jumps straight to the matching
// `catch`, and error.what() is the message given to the throw.
// `untitled` is never created, so there is no invalid Book to misuse.
try {
Book untitled({"978-0000000000", ""}, 1);
} catch (const std::invalid_argument& error) {
std::cout << "rejected: " << error.what() << '\n';
}
Expected output
Design Patterns
2 of 2 available
lend: true
lend: true
lend: false
0 of 2 available
return: true
1 of 2 available
rejected: a book needs a title
How this code works: the Book example in use

Follow the private counter copies_on_loan_ through each call. Callers never see it directly; they only see what the public functions return.

Call Returns copies_on_loan_ after copies_available() after
Book book(..., 2) (none) 0 2
book.lend_copy() true 1 1
book.lend_copy() true 2 0
book.lend_copy() false 2 (unchanged) 0
book.return_copy() true 1 1

The third lend_copy finds copies_on_loan_ == copies_total_ (2 equals 2), so it returns false before the ++ line is reached. That early return is what keeps the count from ever reaching 3.

The last block tries to build untitled with an empty title. The constructor first moves the details and stores the count in the new object, then its body checks the title, finds it empty, and throws std::invalid_argument. The exception leaves the constructor before it finishes, so untitled never becomes a usable object, and control jumps to the catch block, which prints the message passed to the throw: a book needs a title.

The third lend returns false instead of creating an impossible state, and the book with an empty title is never created at all.

Here is the class’s shape as a class outline, the drawing this site uses for classes. Each box lists the data members, then the member functions, as C++ declarations:

class Book

keeps 0 <= copies_on_loan_ <= copies_total_

Data members

  • BookDetails details_; private
  • int copies_total_; private; > 0, checked by the constructor
  • int copies_on_loan_ = 0; private

Member functions

  • Book(BookDetails details, int copies); throws if the title is empty or copies < 1
  • const std::string& isbn() const noexcept;
  • const std::string& title() const noexcept;
  • int copies_total() const noexcept;
  • int copies_available() const noexcept;
  • bool lend_copy(); false if none is available
  • bool return_copy(); false if none is on loan

struct BookDetails

a plain record: public data, no rules

Data members

  • std::string isbn; public
  • std::string title; public
Class outline of Book: the data members are private, the member functions are the public interface

In an outline, - marks a data member and + a member function; access is in the notes. (UML class diagrams use - and + for private and public, which the Modeling section explains.) Here the two coincide: every data member of Book is private, and everything a caller can use is a public member function. A reader can learn how to use Book from the + lines alone, and you can change the - lines without changing any caller. BookDetails is a struct with public data, because it has no rules to protect.

Access control: public, private, and protected

Section titled “Access control: public, private, and protected”

Access control is the set of language rules that decides which code may use each member by name. C++ has three access levels, written as labels inside the class:

  • public: any code may use the member. This is the class’s interface.
  • private: only the class’s own member functions (and code the class explicitly declares a friend) may use it.
  • protected: like private, but classes derived from this class (through inheritance, covered in a later lesson) may also use it on their own objects.

A label applies to every member after it, until the next label.

Three details are easy to miss.

Access is per class, not per object. A member function of Book may read the private members of another Book, not only its own. Access protects a class’s rules from code that does not know them; all code inside the class is trusted to know them.

IllustrativeA fragment for explanation; not compiled on its own.

class Book {
public:
// True if `other` has the same ISBN as this book. `other` is a const
// reference: another Book, read without copying it and without changing it.
// details_ means this book's own member; other.details_ is the other book's.
// Allowed: the private members of `other` belong to the same class.
bool same_isbn(const Book& other) const { return details_.isbn == other.details_.isbn; }
private:
BookDetails details_;
// ...
};

Access is checked when code is compiled, not when it runs. Private members are stored in every object like any other member. Access control stops code from naming them, but it cannot stop code that deliberately goes around the language rules, for example by treating the object’s memory as raw bytes, which usually has undefined behaviour. It is a design tool that turns accidental misuse into a compile error, not a security feature.

Access controls who may use a name, not whether a name is visible. Private members still appear in the header file, and anyone reading it can see them. Changing a private member still requires recompiling the code that includes the header. Hiding the data entirely, for example to keep a stable binary interface, needs other techniques covered in the advanced lessons.

In C++, struct and class are almost the same thing. The only difference is the default access: members of a struct are public until you write a label, and members of a class are private. (The same default applies to base classes in inheritance, covered in a later lesson.) Either can have member functions, constructors, and private members.

Because the language does not distinguish them, programmers use the keyword to signal intent. This site follows a common convention:

  • Use struct for plain data whose members can each take any value independently: a bundle of values with no rule linking them.
  • Use class when the type has an invariant to protect, so its data is private.

BookDetails is a struct, because any ISBN can go with any title, and it has no rule to keep:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

book.hpp
// Plain data with no rule linking its members, so a struct is enough.
// Any ISBN string and any title string make a sensible BookDetails on
// their own, so there is nothing to protect: the members are public (the
// default for a struct) and callers fill them in directly, for example
// BookDetails{"978-0201633610", "Design Patterns"}. Checking that the title
// is not empty is Book's job, because that rule belongs to a lendable book.
struct BookDetails {
std::string isbn;
std::string title;
};

Book is a class, because its numbers must stay consistent. Book keeps its BookDetails in a private member, so callers can read the title but not change it. Note the difference from the flawed version: there, Book was a struct even though it had a rule. The keyword was a hint that the design had missed the rule.

Here is a common half-fix for the flawed Book:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// The fields are private now, but each one has a getter (read it) and a
// setter (overwrite it). The setter does no checking, so the class still
// does not own the rule "0 <= copies_on_loan_ <= copies_total_".
class Book {
public:
int copies_on_loan() const { return copies_on_loan_; }
// The hole: set_copies_on_loan(-5) or set_copies_on_loan(99) is accepted.
// A caller who wants to lend must read, add 1, check, and set, by hand.
void set_copies_on_loan(int n) { copies_on_loan_ = n; } // any value at all
// ... the same pair for every other field ...
private:
int copies_total_ = 0;
int copies_on_loan_ = 0;
};

The data is private, but the setter accepts any value, so the rule is exactly as unprotected as before. Callers still compute “one more loan” themselves and must still remember to check the total. The only change is longer code.

Encapsulation means more than private data. It means the class offers operations that match what callers actually want to do (lend a copy, return a copy) and keeps the rule inside those operations. A useful test: if the class’s public functions read like set_x, set_y, set_z, it is probably a struct with extra steps, and the rules live somewhere else.

A setter that checks a rule (for example, rename(std::string title) that rejects an empty title) is fine. The problem is setters that let any value through.

Because only Book’s own functions can change its state, testing those functions tests the invariant. The tests try the edges: a fresh book, lending past the last copy, returning a copy that was never lent, and invalid construction. (The same file also tests lend_copy followed by return_copy, and the exercise answer below.)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_book.cpp
// The test helpers come from the site's small test header, lld_test.hpp:
// - LLD_TEST(name) { ... } defines one test. The test program runs every
// LLD_TEST it contains; the name says what the test proves.
// - LLD_CHECK(condition) records a failure if the condition is false.
// - LLD_CHECK_EQ(actual, expected) records a failure, and prints both
// values, if they are not equal.
// - LLD_CHECK_THROWS(expression, type) records a failure unless running
// the expression throws an exception of that type.
// A failed check does not stop the test; the next check still runs.
// A fresh book with 3 copies: nothing is on loan, so all 3 are available,
// and the title given to the constructor is the one stored.
LLD_TEST(new_book_has_every_copy_available) {
const Book book({"isbn-1", "Refactoring"}, 3);
LLD_CHECK_EQ(book.copies_available(), 3);
// title() returns a const reference to the stored std::string. == on two
// std::strings compares the characters, and LLD_CHECK_EQ prints both
// if they differ.
LLD_CHECK_EQ(book.title(), std::string("Refactoring"));
}
// The edge at the top: a one-copy book lends once, then refuses. The last
// check proves the refused call changed nothing (still 0, not -1).
LLD_TEST(cannot_lend_more_copies_than_exist) {
Book book({"isbn-1", "Refactoring"}, 1);
LLD_CHECK(book.lend_copy()); // the only copy goes out: true
LLD_CHECK(!book.lend_copy()); // `!` means "not": passes when lend_copy returns false
LLD_CHECK_EQ(book.copies_available(), 0);
}
// The edge at the bottom: returning when nothing is on loan is refused,
// and the book still shows its 1 copy available, not 2.
LLD_TEST(cannot_return_a_copy_that_was_not_lent) {
Book book({"isbn-1", "Refactoring"}, 1);
LLD_CHECK(!book.return_copy());
LLD_CHECK_EQ(book.copies_available(), 1);
}
// Each line tries to build a Book that would break the invariant (an
// empty title, then zero copies) and passes only if the constructor throws
// std::invalid_argument. The temporary Book is never created.
LLD_TEST(constructor_rejects_invalid_books) {
LLD_CHECK_THROWS(Book({"isbn-1", ""}, 1), std::invalid_argument);
LLD_CHECK_THROWS(Book({"isbn-1", "Refactoring"}, 0), std::invalid_argument);
}

With the flawed struct, no equivalent test is possible: the rule can be broken by any code anywhere, so testing lend_copy alone proves nothing about the program.

When to use a class with private state, and when not

Section titled “When to use a class with private state, and when not”

Use a class with private data and a small public interface when:

  • some combinations of values must never exist (an invariant);
  • you expect the internal representation might change, and want callers unaffected (for example, replacing two counters with a list of individual copies);
  • the type has operations with meaning in the problem (lend, return, reserve).

Prefer a plain struct with public members when:

  • the members are independent and any combination is valid (coordinates, a configuration record, the BookDetails above);
  • the type’s job is to carry data between parts of the program, such as a function’s result or a message.

Prefer a free function, not a member function, when an operation needs only the public interface. For example, print_status(const Book&) in main.cpp uses only accessors, so it does not need to be a member. Keeping the member list short keeps the set of functions that can break the invariant short. The design principles section returns to this.

  • Public data with a rule. If a rule links fields, public data means every caller is responsible for the rule, and one of them will forget.
  • A setter for every field. Private data with unchecked setters is public data with longer names.
  • Checking the rule only at the call site. if (book.copies_available() > 0) book.set_copies_on_loan(...) repeated in ten places is ten chances to get it wrong. Put the check inside the operation.
  • Protected data members. They give every derived class the power to break the invariant.
  • Storing values that can be computed. Each stored duplicate (such as both “on loan” and “available”) adds a rule that every operation must keep.
  • Returning a non-const reference to private data. A function such as int& copies_on_loan() lets callers write through the reference, which reopens the hole that private closed.

New requirement: “Copies can be sent for repair. A copy under repair cannot be lent, and is not counted as available.”

With the improved design, the change lands in one class. Book gains a private counter copies_in_repair_, its invariant becomes “on loan plus in repair never exceeds the total”, two new operations send_for_repair and return_from_repair check that rule, and copies_available() subtracts both counters. Callers of lend_copy and copies_available do not change at all: they already asked the class, instead of doing the arithmetic themselves. New tests cover the new operations and check that a copy in repair cannot be lent.

With the flawed struct, every function that lends or counts copies would need to change, and you would need to find them all first.

Exercise: Protect the loan limit

A member may hold a limited number of loans. Someone wrote this:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// A struct, so both fields are public: any code can set either one to any int.
struct LoanAllowance {
int limit = 0; // most loans the member may hold
int held = 0; // loans the member holds now
};
  1. State the invariant this type should keep.
  2. Redesign it as a class that keeps the invariant. Decide which operations callers need, and how a refused operation is reported.
  3. Explain which design choices made the invariant impossible to break from outside.
Show the explained answer
  1. Invariant: 0 <= held <= limit. The limit itself must not be negative.

  2. One reasonable design, compiled and tested with the Book example:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan_allowance.hpp
// How many loans one member may hold, and how many they hold now. Callers
// ask for an operation (record a loan, record a return); the class
// decides whether it is allowed, so the counts can never go wrong.
// Invariant: 0 <= held_ <= limit_.
class LoanAllowance {
public:
// `explicit` stops an int from silently converting to a LoanAllowance
// (see the constructors lesson). Throws if the limit is negative.
// `: limit_(limit)` stores the limit before the body runs; held_ starts
// at 0 from its default below. A limit of 0 is allowed (a member who
// may not borrow at all), so only negatives are refused.
explicit LoanAllowance(int limit) : limit_(limit) {
if (limit_ < 0) throw std::invalid_argument("loan limit must not be negative");
}
[[nodiscard]] int limit() const noexcept { return limit_; }
[[nodiscard]] int held() const noexcept { return held_; }
[[nodiscard]] bool can_borrow() const noexcept { return held_ < limit_; }
// Returns false, and changes nothing, if the member is at the limit.
// It reuses can_borrow, so the rule "held_ < limit_" is written once.
bool record_loan() {
if (!can_borrow()) return false;
++held_;
return true;
}
// Returns false, and changes nothing, if the member holds no loans.
bool record_return() {
if (held_ == 0) return false;
--held_;
return true;
}
private:
int limit_;
int held_ = 0;
};
  1. The choices that protect the invariant:
  • limit_ and held_ are private, so no code outside the class can set them.
  • The constructor rejects a negative limit, and held_ always starts at 0, so every object starts valid.
  • held_ changes only through record_loan and record_return, which check the rule first and return false without changing anything when refused.
  • There is no setter. If the limit must change later (for example, when a member upgrades), add an operation such as change_limit(int) that rejects a limit below held_, rather than set_limit.

Reporting refusal with bool is the simplest choice and fits here, because the only reason for refusal is obvious from the operation. When a caller needs to know why something was refused, a richer result type is better; the error-handling lessons cover the options. Throwing an exception for an ordinary “limit reached” answer would be a poor fit, because it is an expected outcome, not an error.

  • A class groups data with the operations on it; an object is one instance with its own data.
  • Private data plus public operations make a class the single owner of its rules. A rule that must always hold is an invariant.
  • public is the interface, private is the class’s alone, and protected extends access to derived classes; avoid protected data.
  • Access is checked at compile time and per class, not per object.
  • Use a struct for plain data with no rule, and a class when there is an invariant.
  • Getters and setters for every field are not encapsulation; offer operations that match what callers want to do.