1. Goals
Keep related data and operations together in a class.
Keep the remaining ticket count valid by checking before changing it.
Distinguish a
publicinterface,privatedata, andconstmember functions.
2. Prerequisites
You have completed the inventory exercise and know struct, initialization,
functions, references, and const. This lesson uses integers and fixed data;
you do not need manual memory allocation or inheritance. Run it as C++17.
3. Explanation
From separate data to an object
In the inventory exercise, the caller kept an int and asked takeStock
to check before subtracting. Any other code allowed to modify that integer
could still assign -10. TicketStock brings the ticket count and its
allowed operations together in a class. Each object has its own count:
selling tickets at booth does not sell tickets at otherBooth.
The rule to preserve is remaining_ >= 0. A rule that must hold whenever
users of the class can observe its state is called an invariant.
The constructor establishes valid state; every public operation must
preserve it. The underscore in remaining_ is only a naming convention
that makes a member easier to recognize, not a separate C++ protection feature.
Public and private
The public: section is the interface available to outside code: create
an object, read remaining(), and call sell(amount). The private:
section holds data that outside code cannot access directly. Inside main,
the statement booth.remaining_ = -1; is invalid and the compiler rejects it.
The class's own member functions can still read and modify this private data.
This is encapsulation: callers request a ticket sale, and the class
maintains valid state. private is a language access rule, not data encryption
or protection against someone controlling the machine. Both class and
struct can contain data and functions; members are private by default
in a class and public by default in a struct.
C++17 access rules
define these access levels.
Establishing valid initial state
TicketStock(int initial) is a constructor: its name matches the class
and it has no return type. It runs when creating an object, for example
TicketStock booth{8};. The : remaining_(0) part initializes the member
to 0 before the function body runs. Only a positive input is then assigned
to remaining_.
This example treats a negative initial count as 0. That is a deliberate
choice for this sample class; C++ does not automatically repair negative data.
An application that must report invalid input can reject it instead; a later
lesson covers error handling. explicit requires conversion from an integer
to TicketStock to be written explicitly, as in TicketStock{8}, rather than
happening implicitly. The next lesson explains member initialization and
the time of object destruction in more detail.
After completing Foundation, continue with classes and constructors in the C++11 track to reinforce member initialization while studying newer C++ features.
Reading and changing state through clear operations
remaining() const returns a copy of the ticket count. The const after
the parentheses means the function does not modify ordinary members of
the object through itself. This lets you call it through
const TicketStock& view or on const TicketStock otherBooth.
The statement view.sell(1); is invalid because sell is not a const
member function.
view still refers to the same booth, so it sees the new ticket count
after booth.sell(3) succeeds. A const reference does not freeze the
original object. Conversely, changing an integer received from remaining()
does not change the ticket count inside the object.
sell checks amount <= 0 and amount > remaining_ before subtracting.
On rejection, it returns false and preserves the ticket count. On success,
the subtraction result is between 0 and the old count, so it cannot overflow
int. There is no need to add amount to another value for the check,
which could overflow for a sufficiently large input.
4. Runnable example
Save as main.cpp and compile as C++17. The program needs no input.
#include <iostream>
class TicketStock {
public:
explicit TicketStock(int initial) : remaining_(0) {
if (initial > 0) {
remaining_ = initial;
}
}
int remaining() const {
return remaining_;
}
bool sell(int amount) {
if (amount <= 0 || amount > remaining_) {
return false;
}
remaining_ -= amount;
return true;
}
private:
int remaining_;
};
int main() {
TicketStock booth{8};
const TicketStock& view = booth;
const TicketStock otherBooth{2};
const TicketStock invalidStart{-4};
std::cout << std::boolalpha;
std::cout << "Initial: " << view.remaining() << '\n';
std::cout << "Sell 3: " << booth.sell(3) << '\n';
std::cout << "Remaining: " << view.remaining() << '\n';
std::cout << "Sell 0: " << booth.sell(0) << '\n';
std::cout << "Sell -2: " << booth.sell(-2) << '\n';
std::cout << "Sell 6: " << booth.sell(6) << '\n';
std::cout << "After refusals: " << view.remaining() << '\n';
std::cout << "Sell 5: " << booth.sell(5) << '\n';
std::cout << "Sell from empty: " << booth.sell(1) << '\n';
std::cout << "Final: " << view.remaining() << '\n';
std::cout << "Other booth: " << otherBooth.remaining() << '\n';
std::cout << "Negative initial: " << invalidStart.remaining() << '\n';
return 0;
}Exact output:
Initial: 8
Sell 3: true
Remaining: 5
Sell 0: false
Sell -2: false
Sell 6: false
After refusals: 5
Sell 5: true
Sell from empty: false
Final: 0
Other booth: 2
Negative initial: 05. Common mistakes
Making data
privatebut offering an unchecked setter for any integer: the class can still enter an invalid state if that operation does not validate it.Subtracting before checking: a failed operation has already changed the object.
Omitting
constfrom a reader: it cannot be called through aconstobject or reference.Assuming every class needs
setRemaining: expose only the operations the problem needs.Forgetting the
;after the closing}of a class definition.
6. Practice
Create two booths with
4and9tickets. Sell3from the first; their counts must become1and9. Explain why the booths are independent.For a fresh booth with
5tickets, test each case independently: selling0,-1, or6must fail and preserve5; selling5must succeed and leave0.Save
int snapshot = booth.remaining();, then sell one ticket successfully. The snapshot keeps the old count, whileview.remaining()gives the new count.In a separate copy of the program, add
booth.remaining_ = -1;andview.sell(1);tomain, one at a time. Compile to inspect each error, then remove the statements. Explain the access orconstrule behind each error.
7. Self-check
Why should
remaining_beprivatehere? Answer: outside code must not bypass validation and assign a negative ticket count. Public operations must still preserve the invariant themselves;privatedoes not write validation code for you.Does
remaining() constpreventboothfrom ever changing again? Answer: no. The reader does not modify state through itself, butbooth.sell(...)can still change the object through its modifying interface.A booth with
2tickets receivessell(3). What is returned, and how many remain? Answer: it returnsfalseand retains2. Rejection is checked before subtraction.
Sample code
Source file
cpp98_foundation/13_classes_encapsulation/main.cpp
#include <iostream>
class TicketStock {
public:
explicit TicketStock(int initial) : remaining_(0) {
if (initial > 0) {
remaining_ = initial;
}
}
int remaining() const {
return remaining_;
}
bool sell(int amount) {
if (amount <= 0 || amount > remaining_) {
return false;
}
remaining_ -= amount;
return true;
}
private:
int remaining_;
};
int main() {
TicketStock booth{8};
const TicketStock& view = booth;
const TicketStock otherBooth{2};
const TicketStock invalidStart{-4};
std::cout << std::boolalpha;
std::cout << "Initial: " << view.remaining() << '\n';
std::cout << "Sell 3: " << booth.sell(3) << '\n';
std::cout << "Remaining: " << view.remaining() << '\n';
std::cout << "Sell 0: " << booth.sell(0) << '\n';
std::cout << "Sell -2: " << booth.sell(-2) << '\n';
std::cout << "Sell 6: " << booth.sell(6) << '\n';
std::cout << "After refusals: " << view.remaining() << '\n';
std::cout << "Sell 5: " << booth.sell(5) << '\n';
std::cout << "Sell from empty: " << booth.sell(1) << '\n';
std::cout << "Final: " << view.remaining() << '\n';
std::cout << "Other booth: " << otherBooth.remaining() << '\n';
std::cout << "Negative initial: " << invalidStart.remaining() << '\n';
return 0;
}