Skip to content
AgileLogics
4 min read

Access Specifiers & Encapsulation

Prerequisites: Constructors & destructors

Like Java's access modifiers, C++ has public, private, and protected — applied to a whole block rather than one member at a time.

class BankAccount {
private:
    double balance;

public:
    BankAccount(double initial) : balance(initial) {}

    double getBalance() const {
        return balance;
    }

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

A class's members are private by default; a struct's are public by default — the only difference between the two keywords in C++. Convention: use struct for a plain data holder with no invariants to protect, class for anything with real behavior or rules to enforce.

Common mistakes

  • Making every member public "to keep things simple" — this removes the ability to enforce rules like rejecting a negative deposit, exactly as in Java.