C++ constructors and encapsulation

Initialize private state and expose a controlled interface.

C++
#include <iostream>
#include <stdexcept>
class Counter {
    int value_;
public:
    explicit Counter(int start) : value_(start) {
        if (start < 0) throw std::invalid_argument("negative start");
    }
    void increment() { ++value_; }
    int value() const { return value_; }
};
int main() {
    Counter counter(2);
    counter.increment();
    std::cout << counter.value() << '\n';
}
Output
3

Explanation

A constructor establishes an object's initial state. A member initializer list initializes data members before the constructor body begins.

Private fields cannot be accessed directly by ordinary external code. A const member function promises not to modify the object's non-mutable data members.

Explore the dry run
Guided walkthroughReady
1#include <iostream>
2#include <stdexcept>
3class Counter {
4 int value_;
5public:
6 explicit Counter(int start) : value_(start) {
7 if (start < 0) throw std::invalid_argument("negative start");
8 }
9 void increment() { ++value_; }
10 int value() const { return value_; }
11};
12int main() {
13 Counter counter(2);
14 counter.increment();
15 std::cout << counter.value() << '\n';
16}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Initialize private value_ with 2 and validate it.value_ = 2
—
Call the public mutating operation.value_ = 3
—
Read state through a const accessor.return = 3
—
Print the result.return = 3
3

Cost and common mistakes

O(1) time per operation and O(1) object storage.

  • Access control supports an API contract; it is not a security boundary.
  • This minimal counter does not guard repeated increments at the maximum int value.

Try it yourself

Create another Counter(10) and increment only the first.

Reveal answer and reasoning

The objects remain independent; the second still reports 10.

Further reading