C++ constructors and encapsulation

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

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';
}
Read the full lesson