Model data with classes
Encapsulate state and preserve valid object invariants.
- Define a class with private state, a constructor, and public behavior.
A class defines a type that groups state and operations. Keep implementation details private and expose a small public interface. A constructor establishes the object’s initial invariant; member initializer lists initialize fields directly. C++ structs and classes are similar, except struct members are public by default and class members are private by default.
1#include <iostream>
2#include <string>
3
4class Counter {
5public:
6 explicit Counter(std::string label) : label_(label), value_(0) {}
7 void increment() { ++value_; }
8 void print() const { std::cout << label_ << ": " << value_ << "\n"; }
9private:
10 std::string label_;
11 int value_;
12};Counter keeps its state private and exposes operations.
The const after print() promises that the method does not modify the object’s observable state. explicit prevents an accidental implicit conversion from a string to a Counter.
Key takeaways
Encapsulation protects object invariants.
Initialize members in constructors.
Const member functions support read-only access.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write C++
Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.
Create a small counter class
Implement a Counter with a private integer, a public increment() method, and a value() const accessor. Read a count, increment that many times, and print the final value.
- Three increments
- No increments
Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…