Thuta Learning
C++
AdvancedProgrammingBeginner

Access Specifiers

C++Lesson 2125 min

What you'll walk away with

  • State who can access public, private and protected members
  • Explain what an invariant is and show how private data plus public member functions protect it
  • Understand that access is checked per class, not per object
  • Avoid designs such as blind setters and returned references that make encapsulation empty

Explain it simply

Explain it simply

At a bank, nobody walks into the vault and takes money out themselves. You ask at the counter, and the clerk first checks that your account has enough. The vault is private data; the counter is a public member function.

C++ has three access specifiers. Members after public: can be used by anyone, while members after private: can be touched only by the class's own member functions. protected: sits in between and also admits classes derived from this one. Code that breaks these rules simply does not compile.

Problem → Why → Solution

The problem: any code can corrupt the data

If the account balance is a public field, every function in the program can change it without any checks. payRent() below subtracts without checking whether there is enough money, and the account goes negative. In a large program a line like that can hide in any one of hundreds of files.

public_balance.cpp
#include <iostream>

struct BankAccount {
    double balance = 0;          // public: any code may change it
};

void payRent(BankAccount& acc) {
    acc.balance -= 500;          // no check: the account goes negative
}

int main() {
    BankAccount acc;
    acc.balance = 100;
    payRent(acc);
    std::cout << acc.balance << '\n';   // -400
}

Why is this such a big problem?

The rule "balance never goes negative" has to be enforced by every line that touches balance. Forget it once and the data is corrupted, and when you hunt the bug you must search the whole program for the line that changed it. Make balance private and allow changes only through withdraw(), and the check lives in exactly one place that nobody can bypass.

Core concept: the class guards its own invariants

Access specifiers are labels inside a class, and each one applies to every member until the next label. The rules are checked at compile time, so a line in main() such as account.balance = 1e9; stops the build with an error like "'double BankAccount::balance' is private within this context", and there is zero runtime cost.

SpecifierWho can access itTypical use
publicAny codeThe class's interface: constructors, operations
protectedThe class and its derived classesHelper functions meant for derived classes
privateThe class's own members and friendsData members and internal helpers

The reason for access control is invariants. An invariant is a rule that must hold for an object from the end of its construction until it is destroyed: a balance is never negative, a Fraction's denominator is never 0, a sorted list stays sorted. Once the data is private, the only code that can change it is the class's handful of member functions, so checking the rule there is enough to guarantee it for every object. This is called encapsulation.

Remember that the constructor is where an invariant begins. If deposit() rejects negative amounts but the constructor accepts BankAccount account(-100);, the object breaks the rule from birth. Recall the class and struct difference too: without a label, class members are private and struct members are public, which is why types with invariants are usually written as classes.

Access is checked per class, not per object. A BankAccount member function can touch the private members not only of its own object but of any other BankAccount it receives as a parameter, which is what makes operations like a transfer possible inside the class.

Mental model: data behind a guarded door
  1. Caller calls a public function
  2. The function checks the invariant
  3. Only then is private data changed
  4. Direct access is a compile error

Every path that can change private data runs through the class itself, so nobody can skip the check.

General pattern

cpp
class ClassName {
public:      // the interface: any code may call these
    bool change(Type amount);          // checks the invariant first
    Type current() const;              // read-only view of the state
protected:   // this class and classes derived from it
    void helperForDerived();
private:     // only this class's own member functions (and friends)
    Type state_ = initialValue;        // guarded by the invariant
    void internalHelper();
};

Put only the operations users of the class genuinely need in the public section and keep the data private. Functions that change the data check the rules, and functions that only read are const. Reserve protected for helpers you deliberately open up to derived classes.

Example: a BankAccount with a private balance

In this example balance is private while deposit() and getBalance() are public. Watch how main() never touches balance directly and goes through the public functions instead. The breakdown also points out where this class could be made stricter.

cpp
#include <iostream>
using namespace std;

class BankAccount {
  private:
    double balance;

  public:
    BankAccount(double startBalance) {
        balance = startBalance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account(100);
    account.deposit(50);
    cout << account.getBalance();
    return 0;
}

Code breakdown

  1. Lines 5-6double balance;

    It sits under the private: label, so only BankAccount's member functions can name balance. Writing account.balance in main() is a compile error.

  2. Line 9BankAccount(double startBalance) {

    The constructor must be public so main() can create an object. It does not check startBalance, though, so BankAccount account(-100); is accepted; to really protect the invariant, the check belongs here too.

  3. Line 14if (amount > 0) {

    The deposit rule lives in this single line. There is no other way in from outside, so a negative or zero amount can never be added.

  4. Line 19double getBalance() {

    Grants read access without write access. It does not change the object, so it should be double getBalance() const, which also makes it callable through a const BankAccount&.

  5. Line 27cout << account.getBalance();

    main() reads the balance through the public function. It started at 100 and 50 was deposited, so it prints 150.

You should see
150

Designing the public interface

This version stores the balance as integer cents (long long) instead of double, because double cannot hold values like 0.1 exactly and is a poor fit for money. The balance starts at 0, and withdraw() and deposit() reject bad requests by returning false. Notice that transferTo() touches the other account's private cents_ directly; that is allowed because both objects belong to the same class.

account.cpp
#include <format>
#include <iostream>
#include <string>

class BankAccount {
public:
    explicit BankAccount(std::string owner) : owner_(owner) {}

    bool deposit(long long cents) {
        if (cents <= 0) return false;
        cents_ += cents;
        return true;
    }

    bool withdraw(long long cents) {
        if (cents <= 0 || cents > cents_) return false;   // never below zero
        cents_ -= cents;
        return true;
    }

    bool transferTo(BankAccount& other, long long cents) {
        if (!withdraw(cents)) return false;
        other.cents_ += cents;     // allowed: access is checked per class
        return true;
    }

    long long balance() const { return cents_; }
    const std::string& owner() const { return owner_; }

private:
    std::string owner_;
    long long cents_ = 0;          // invariant: cents_ >= 0
};

void show(const BankAccount& a) {
    std::cout << std::format("{}: {}.{:02}\n", a.owner(), a.balance() / 100,
                             a.balance() % 100);
}

int main() {
    BankAccount aye("Aye");
    BankAccount bo("Bo");
    aye.deposit(15000);
    std::cout << std::boolalpha;
    std::cout << "withdraw 200.00: " << aye.withdraw(20000) << '\n';
    std::cout << "transfer 40.00: " << aye.transferTo(bo, 4000) << '\n';
    show(aye);
    show(bo);
    // aye.cents_ = -500;   error: 'cents_' is private within this context
}

The output is "withdraw 200.00: false", "transfer 40.00: true", "Aye: 110.00" and "Bo: 40.00". Notice there is no setBalance(): letting outside code set the balance to any value would make the private keyword pointless. The public interface offers real operations instead: deposit, withdraw and transfer.

protected, friend, and what access control is not

Derived classes can use protected members (inheritance is the next lesson). Protected data, however, can be changed by any class that derives from yours, which weakens the invariant protection. It is safer to keep data private even in a base class and give derived classes what they need as protected member functions.

friend grants one specific function or class access to the private members. It is useful for functions that work closely with the class, such as operator<<, but every friend is one more place that could break the invariant, so use it sparingly.

private is not security

Access control is a tool for catching programmer mistakes at compile time. Private members still sit in ordinary memory, where pointers, debuggers and memory dumps can reach them. Never assume a password or key is safe just because the member holding it is private.

In real projects

Where this shows up in real projects

std::vector is a textbook case of encapsulation. Its data pointer, size and capacity are private, so nobody can set the size to 1000 and then read elements that have no memory behind them. Public functions such as push_back() and resize() grow the memory as needed and keep size and capacity consistent. Thread-safe classes work the same way: the data and its mutex are private, and every member function locks before touching the data, so unlocked access cannot happen.

Encapsulation also makes change cheaper. Changing private members, say from double to integer cents, requires no edits in the code that uses the class; as long as the public interface stays the same, it only needs recompiling. Libraries that want to avoid even the recompile use the pImpl (pointer to implementation) idiom, moving the private members into a separate struct defined in the .cpp file.

Common mistakes

Common mistakes

1. Adding a setter that accepts anything

Making balance_ private and then adding a public void setBalance(double b) { balance_ = b; } still lets outside code call setBalance(-400); the encapsulation exists in name only. Instead of a getter/setter pair for every field, offer meaningful operations such as withdraw().

2. Returning private data by non-const reference

A function like std::vector<Item>& items() { return items_; } lets the caller clear() items_ or push unchecked entries into it. If callers only need to read, return const std::vector<Item>& from a const function; if they need to change it, provide a specific operation such as addItem().

3. Not checking the invariant in the constructor

Every member function may check the rule, yet if the constructor accepts BankAccount(-100), the object is invalid from its first moment. Check in the constructor (exceptions, covered in lesson 24, are the right tool), or start at 0 and allow money in only through deposit(), as the deeper example in this lesson does.

4. Making all the data protected

Making every data member protected "because derived classes might need it" lets every derived class change the data while bypassing the invariant. Default to private, and open a protected member function only when a derived class genuinely needs one.

Best practices

Best practices

  • Keep data members private in every type with an invariant; a plain bundle of data with no invariant can be a struct with public members.
  • Put the public section at the top of the class, because readers first want to know how to use it.
  • Mark private data members with a suffix such as cents_ or another team convention so they never clash with parameter names.
  • Make every read-only member function const.

Mini challenge

Mini challenge: a volume control class

Write a VolumeControl class for a TV remote. The level must never drop below 0 or rise above 100, and unmuting must bring back the level from before the mute.

  • level_ (starting at 50) and muted_ (starting false) are private
  • Every write to level_ goes through one private helper, set(), which uses std::clamp
  • Public up(int), down(int), mute(), unmute(), level() const and report() const
  • While muted, level() returns 0 and report() adds "(muted)"
volume.cpp
#include <algorithm>   // std::clamp
#include <iostream>

class VolumeControl {
public:
    void up(int step) { /* TODO */ }
    void down(int step) { /* TODO */ }
    void mute() { /* TODO */ }
    void unmute() { /* TODO */ }

    int level() const { /* TODO: 0 while muted */ }
    void report() const { /* TODO: "volume N" plus " (muted)" */ }

private:
    // TODO: a helper that is the ONLY code writing the level (keep 0..100)
    // TODO: the level (starts at 50) and the muted flag
};

int main() {
    // TODO: up 20, up 50, mute, unmute, down 150 - report after each step
}

Expected: volume 70 volume 100 volume 0 (muted) volume 100 volume 0

Show hint

std::clamp(value, 0, 100) pins value between 0 and 100. When muting, do not set level_ to 0; flip the flag only and return muted_ ? 0 : level_ from level(), so unmuting brings the old level back by itself.

Show solution
volume.cpp
#include <algorithm>
#include <iostream>

class VolumeControl {
public:
    void up(int step) { set(level_ + step); }
    void down(int step) { set(level_ - step); }
    void mute() { muted_ = true; }
    void unmute() { muted_ = false; }

    int level() const { return muted_ ? 0 : level_; }

    void report() const {
        std::cout << "volume " << level() << (muted_ ? " (muted)" : "") << '\n';
    }

private:
    void set(int value) { level_ = std::clamp(value, 0, 100); }  // only writer

    int level_ = 50;        // invariant: 0 <= level_ <= 100
    bool muted_ = false;
};

int main() {
    VolumeControl tv;
    tv.up(20);
    tv.report();
    tv.up(50);
    tv.report();
    tv.mute();
    tv.report();
    tv.unmute();
    tv.report();
    tv.down(150);
    tv.report();
}

Quick quiz 1 / 3

Given class Wallet { public: long long balance() const; private: long long cents_ = 0; };, which line in main() compiles?

Quick quiz 2 / 3

Inside BankAccount::transferTo(BankAccount& other, long long c), what happens with other.cents_ += c; when cents_ is private?

Quick quiz 3 / 3

Which design actually protects the invariant "quantity is never negative"?

What to remember

  • public is open to all, protected to the class and its derived classes, private to the class itself, all checked at compile time.
  • Private data changed only through public operations that check the rules is encapsulation, and it guarantees invariants.
  • The constructor is where an invariant must start, and access is checked per class.
  • Blind setters and returned non-const references destroy encapsulation, and private is not a security tool.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Access Specifiers | Thuta Learning