C++ constructors and encapsulation
Initialize private state and expose a controlled interface.
On this page
Classes, methods, and access specifiers.
- Initialize private state and expose a controlled interface.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
#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';
}3
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#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';}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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
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.