Skip to content

Private State and const Methods

The Course
•
35 min study

The last lesson ended with a checked task whose duration was later set to -30 by a single assignment. The check was correct; it just had no power over what happened afterward. To make a rule hold for the whole life of an object, the object has to own its data and decide every change itself.

That is what a class with private members gives you. Code outside the class cannot read or write a private member at all. It can only call the public member functions the class offers, and those functions apply the rule. If a counter must never pass 100, the increment function is the only door, and the door checks the limit. The rule now lives in one place instead of in every caller.

This lesson covers three tools that work together: private members, constructors that start an object in a valid state, and const member functions that promise not to change it.

Predict and run

Counter starts at zero and offers a capped increment and a read-only value. What does main print?

Predict before running C++
#include <iostream>

class Counter {
public:
    Counter() : value_(0) {}
    void increment() { if (value_ < 100) { ++value_; } }
    int value() const { return value_; }
private:
    int value_;
};

int main() {
    Counter counter;
    counter.increment();
    counter.increment();
    std::cout << counter.value() << "\n";
    return 0;
}
Check your prediction
Text
2

The constructor Counter() : value_(0) {} runs when counter is declared, so the object starts at 0. Each increment adds one because the value is below the cap. The trailing underscore in value_ is only a naming habit that marks a member; it lets the public function be called value() without a clash.

The compiler enforces the door

Add counter.value_ = 500; to main and run. The program no longer builds:

Shell
main.cpp:14:13: error: 'value_' is a private member of 'Counter'
   14 |     counter.value_ = 500;
      |             ^
main.cpp:9:9: note: declared private here

This is the guarantee the public struct could not give. Access control is checked entirely at compile time, so it costs nothing when the program runs; the compiled code is the same as for a public field. Remove the line before you continue.

struct and class are almost the same thing in C++. The only difference is the default: members of a struct are public until you say otherwise, and members of a class are private. By convention, use struct for plain bundles of independent data and class when there is an invariant to protect.

Start valid: constructors and initializers

A rule that must always hold must also hold at the very start. A constructor runs exactly once, when the object is created, and its member initializer list (the part after the colon) initializes each member before the constructor body runs. A default member initializer, written int value_ = 0; in the class, does the same job with less code and covers every constructor at once.

Skipping both is a real bug, not just a style issue. A local int member that is never initialized holds an indeterminate value, and reading it is undefined behavior:

C++
class Broken {
public:
    int value() const { return value_; } // Reads garbage: undefined behavior.
private:
    int value_; // Never initialized.
};

Undefined behavior means the language places no requirement on what happens. The program might print 0 in a debug build and a random number in a release build, because the optimizer is allowed to assume a valid program never reads an uninitialized value and can transform the code on that assumption. Initialize every member, every time.

Members are initialized in the order they are declared in the class, not the order you list them after the colon. Clang and GCC warn when the two orders differ (-Wreorder), because an initializer that uses another member can then read it before it is set.

const member functions

The const after int value() is a promise: this function will not change the object. The compiler holds the function body to that promise, and in return lets you call it on objects you are only allowed to read. A const Counter& parameter says "I will look at your counter, not change it", and through that reference only const functions are callable. If you write view.increment() on a const Counter& view, the build fails:

Shell
main.cpp:15:5: error: 'this' argument to member function 'increment' has type 'const Counter', but function is not marked const

Mark every function that only reads as const. If you forget, nothing breaks until somebody passes the object by const reference, and then perfectly reasonable read-only code fails to compile.

Read through a const reference C++
#include <iostream>

class Progress {
public:
    explicit Progress(int goal) : goal_(goal) {}
    bool log(int minutes) {
        if (minutes <= 0 || minutes > goal_ - logged_) { return false; }
        logged_ += minutes;
        return true;
    }
    int logged() const { return logged_; }
    int remaining() const { return goal_ - logged_; }
private:
    int goal_;
    int logged_ = 0;
};

void show(const Progress& progress) {
    std::cout << progress.logged() << " logged, " << progress.remaining() << " left\n";
}

int main() {
    Progress week(60);
    week.log(25);
    show(week);
    bool accepted = week.log(50);
    std::cout << (accepted ? "accepted" : "rejected") << "\n";
    show(week);
    return 0;
}
Text
25 logged, 35 left
rejected
25 logged, 35 left

log checks the remaining amount before adding, so the rejected 50 leaves the object untouched, and show can only call the two const getters. The word explicit stops the compiler from quietly turning a plain int into a Progress when a function expects one; use it on single-argument constructors. One gap remains: Progress(-10) still builds an object with a nonsense goal, because a constructor has no ordinary way to say no. The next lesson fixes that.

Practice

Exercise

Your turn

Write a Budget class constructed with a limit in minutes. bool spend(int minutes) accepts a positive amount that fits in what is left and rejects anything else without changing the object. Add const getters spent() and remaining(), and a free function void show(const Budget&) that prints them. With a limit of 60, spend 25, 40, 35, 1 and 0, printing each result and then the final state:

Text
spend 25: ok
spend 40: rejected
spend 35: ok
spend 1: rejected
spend 0: rejected
spent 60, remaining 0
Your workspace C++
#include <iostream>

// Write Budget and show here.

int main() {
    // Budget budget(60);
    // Try 25, 40, 35, 1 and 0, then call show(budget).
    return 0;
}
Hint 1: the idea

Keep both numbers private. The only function that changes them is spend, so it is the only place the rule has to be written. Decide first, change second.

Hint 2: a first step

Store limit_ from the constructor and give spent_ a default member initializer of 0. In spend, return false when minutes <= 0 || minutes > remaining(). Calling a const function from a non-const one is fine.

Show one solution
Run the solution C++
#include <iostream>

class Budget {
public:
    explicit Budget(int limit) : limit_(limit) {}
    bool spend(int minutes) {
        if (minutes <= 0 || minutes > remaining()) { return false; }
        spent_ += minutes;
        return true;
    }
    int spent() const { return spent_; }
    int remaining() const { return limit_ - spent_; }
private:
    int limit_;
    int spent_ = 0;
};

void show(const Budget& budget) {
    std::cout << "spent " << budget.spent() << ", remaining " << budget.remaining() << "\n";
}

int main() {
    Budget budget(60);
    const int requests[] = {25, 40, 35, 1, 0};
    for (int minutes : requests) {
        std::cout << "spend " << minutes << ": " << (budget.spend(minutes) ? "ok" : "rejected") << "\n";
    }
    show(budget);
    return 0;
}
Text
spend 25: ok
spend 40: rejected
spend 35: ok
spend 1: rejected
spend 0: rejected
spent 60, remaining 0

Comparing against remaining() instead of computing spent_ + minutes avoids integer overflow for a huge request, and the check runs before any change, so every rejection leaves the budget as it was. spend(35) uses exactly what is left, which proves the comparison is > and not >=. Because show takes a const Budget&, it could not call spend even by accident. The next lesson closes the last gap: refusing to build an object from bad input in the first place.

Was this article helpful?

Your response is saved on this device.