The Analogy: The Restaurant Floor Plan
A restaurant has three kinds of space. The dining room is public: anyone may walk in. The kitchen is private: staff only, and the reason is not secrecy but safety and consistency — a customer wandering in and stirring a pan would ruin the dish. Between them is the staff corridor: not for customers, but shared by everyone who works there, including new branches that open under the same brand.
Those are C++'s three access levels exactly. public is the dining room, private is the kitchen, and protected is the staff corridor that derived classes may also use. Choosing them is how you decide what a class promises to the outside world and what it keeps as its own business.
Syntax or Core Structure
An access specifier applies to everything after it, until the next one.
#include <iostream>
#include <string>
class BankAccount {
private: // (redundant here -- 'class' defaults to private)
double balance{0.0};
std::string pin{"0000"};
bool pinMatches(const std::string& attempt) const {
return attempt == pin; // a private helper
}
protected:
void forceBalance(double v) { balance = v; } // derived classes may use this
public:
explicit BankAccount(double opening) : balance(opening) {}
double getBalance() const { return balance; } // controlled read access
bool withdraw(double amount, const std::string& attempt) {
if (!pinMatches(attempt)) { return false; }
if (amount <= 0.0 || amount > balance) { return false; }
balance -= amount;
return true;
}
};
int main() {
BankAccount a{100.0};
std::cout << a.getBalance() << "\n"; // 100 -- public
std::cout << a.withdraw(30.0, "0000") << "\n"; // 1
std::cout << a.getBalance() << "\n"; // 70
// a.balance = 1000000.0; // ERROR: 'balance' is private
// a.pinMatches("0000"); // ERROR: private member function
// a.forceBalance(0.0); // ERROR: protected, and main is not a subclass
return 0;
}
You may repeat the specifiers as often as you like and in any order. The common house style is public first — the interface a reader cares about — then protected, then private.
Technical Depth: Who Can See What
The three levels, precisely
| Accessible from | public | protected | private |
|---|---|---|---|
| Other members of the same class | Yes | Yes | Yes |
A friend of the class | Yes | Yes | Yes |
| A derived class's members | Yes | Yes | No |
Outside code (main, free functions) | Yes | No | No |
Access is per class, not per object
A member function may reach the private members of any object of its own class, not just this. That is what makes comparison and copying possible:
class Money {
long pence{0};
public:
explicit Money(long p) : pence(p) {}
bool operator<(const Money& other) const {
return pence < other.pence; // other.pence is private -- and legal
}
};
Newcomers often expect other.pence to be an error. It is not: privacy is a property of the class, not of individual instances.
class versus struct is only about defaults
struct A { int x; }; // x is public
class B { int x; }; // x is private
struct C : Base { }; // public inheritance by default
class D : Base { }; // PRIVATE inheritance by default -- a common surprise
Because class defaults inheritance to private, class D : Base almost never means what the author intended. Write the specifier out: class D : public Base.
Inheritance changes what the outside world sees
The specifier in front of the base class caps the visibility of everything inherited:
| Base member is | : public Base | : protected Base | : private Base |
|---|---|---|---|
public | public | protected | private |
protected | protected | protected | private |
private | inaccessible | inaccessible | inaccessible |
Public inheritance means "is a" and is what you want ninety-nine times out of a hundred. Private inheritance means "is implemented in terms of", and composition — holding the other class as a member — usually says it more clearly.
Note the last row: a derived class can never touch the base's private members, no matter how it inherits.
friend: a deliberate, named exception
friend grants one specific function or class full access. It must be declared inside the class granting it, so a class can never award itself access to another.
class Temperature {
double celsius{0.0};
public:
explicit Temperature(double c) : celsius(c) {}
friend std::ostream& operator<<(std::ostream& os, const Temperature& t);
friend class Calibrator; // an entire class
};
std::ostream& operator<<(std::ostream& os, const Temperature& t) {
return os << t.celsius << " C"; // reaches the private member
}
Stream operators are the classic legitimate use, because they cannot be members. Friendship is not inherited and not transitive: a friend of a base is not a friend of the derived class, and your friend's friend is a stranger.
protected is weaker than it looks
protected data is often a mistake. It exposes a member to every present and future derived class, which means you can no longer change it without auditing all of them — nearly as bad as public, but harder to see. Prefer private data plus protected functions that enforce the rules:
class Shape {
double area{0.0}; // private: nobody writes it directly
protected:
void setArea(double v) { // derived classes go through here
area = (v > 0.0) ? v : 0.0;
}
public:
double getArea() const { return area; }
};
This is a compile-time rule, not security
Access control stops mistakes, not attackers. Nothing about private encrypts or hides the bytes; a cast or a memory editor walks straight past it, and sizeof reports private members like any other. The purpose is to let you change a class's internals without breaking its callers.
Nested classes and access
A nested class is a member, so it obeys the enclosing class's access level, and it may reach the enclosing class's private statics:
class Parser {
struct Token { std::string text; int kind; }; // private helper type
public:
bool parse(const std::string& source); // Token is invisible outside
};
Keeping a helper type private is a tidy way to say "this is an implementation detail".
Real World Example: A Door Lock Controller
A base class, a derived class, a friend, and one protected hook — each access level earning its place.
#include <iostream>
#include <string>
#include <vector>
class DoorLock {
private:
// Nobody outside, and no derived class, may touch these directly.
bool locked{true};
std::string code{"1234"};
int failedAttempts{0};
std::vector<std::string> auditLog{};
void record(const std::string& event) { // private helper
auditLog.push_back(event);
}
protected:
// Derived classes get a controlled way in -- a function, not the flag.
void setLocked(bool value, const std::string& reason) {
locked = value;
record(reason);
}
bool isCodeCorrect(const std::string& attempt) const {
return attempt == code;
}
int attemptsSoFar() const { return failedAttempts; }
public:
bool isLocked() const { return locked; }
std::size_t auditSize() const { return auditLog.size(); }
bool unlock(const std::string& attempt) {
if (failedAttempts >= 3) {
record("refused: locked out");
return false;
}
if (!isCodeCorrect(attempt)) {
++failedAttempts;
record("failed attempt");
return false;
}
failedAttempts = 0;
setLocked(false, "unlocked by code");
return true;
}
void lock() { setLocked(true, "locked"); }
// A named exception: the engineer's tool may inspect everything.
friend class ServiceTool;
};
// "is a" relationship -> public inheritance, written out explicitly.
class TimedDoorLock : public DoorLock {
int autoLockSeconds{30};
public:
bool unlockFor(const std::string& attempt, int seconds) {
if (!unlock(attempt)) { return false; } // public base method
autoLockSeconds = seconds;
return true;
}
void tick(int elapsed) {
if (!isLocked() && elapsed >= autoLockSeconds) {
setLocked(true, "auto-locked"); // protected -- allowed here
}
}
std::string report() const {
// isCodeCorrect and attemptsSoFar are protected: usable, not exposed.
return std::string(isLocked() ? "secure" : "open") +
", failures: " + std::to_string(attemptsSoFar());
}
};
// A friend of DoorLock only. Not a friend of TimedDoorLock.
class ServiceTool {
public:
static void resetCode(DoorLock& lock, const std::string& newCode) {
lock.code = newCode; // private -- legal for a friend
lock.failedAttempts = 0;
lock.record("code reset by engineer");
}
static std::size_t logSize(const DoorLock& lock) { return lock.auditLog.size(); }
};
int main() {
TimedDoorLock front;
std::cout << front.unlockFor("0000", 10) << "\n"; // 0 -- wrong code
std::cout << front.unlockFor("1234", 10) << "\n"; // 1
std::cout << front.report() << "\n"; // open, failures: 0
front.tick(15); // past 10 seconds
std::cout << front.report() << "\n"; // secure, failures: 0
ServiceTool::resetCode(front, "9999");
std::cout << front.unlockFor("9999", 5) << "\n"; // 1
std::cout << "log entries: " << ServiceTool::logSize(front) << "\n";
// front.locked = false; // ERROR: private
// front.setLocked(false, "hack"); // ERROR: protected, main is not derived
// front.code = "0000"; // ERROR: private, main is not a friend
return 0;
}
Each level here answers a different question about who is trusted with what. locked, code, failedAttempts and auditLog are private because every rule in the class depends on them moving together — a derived class allowed to write locked = false directly would bypass the audit log and the lockout counter, and the class could never again promise that its log is complete. So instead the derived class gets protected functions: setLocked always records a reason, and isCodeCorrect and attemptsSoFar expose the answers without exposing the fields. That is the deliberate choice of protected-function-over-protected-data — TimedDoorLock::tick can auto-lock, but it cannot auto-lock silently. The public surface is deliberately tiny: isLocked, auditSize, unlock and lock, which is everything a caller in main legitimately needs and nothing more. TimedDoorLock : public DoorLock spells out public because class would otherwise default to private inheritance and front.isLocked() would stop compiling. ServiceTool is a friend because a maintenance tool genuinely does need to rewrite the code and clear the counter, and friend names that exception precisely rather than loosening code to protected for everyone forever — note also that friendship does not inherit, so ServiceTool reaching TimedDoorLock::autoLockSeconds would not compile. The four commented-out lines at the end are the point of the whole design: three plausible mistakes, all caught by the compiler.
Common Mistakes
- Writing
class D : Baseand getting private inheritance. Always writepublicexplicitly. - Making data
protectedfor convenience. Every derived class, forever, now depends on that field's name and type. - Expecting a derived class to see the base's
privatemembers. It cannot, under any inheritance specifier. - Assuming
other.privateFieldis illegal inside a member function. Access is per class, so it is fine. - Treating
privateas a security boundary. It prevents accidents, not determined access. - Scattering specifiers.
public,private,public,privatedown one class makes the interface impossible to read at a glance. - Handing out
friendfreely. Each one is a permanent coupling to a specific other type. - Expecting friendship to be inherited or mutual. Neither is true; both must be declared where the access is granted.
- Returning a non-
constreference to a private member.std::string& getName()makes the member public in all but name.
Best Practices
- Start everything
privateand promote only what callers need. It is far easier than the reverse. - Order the class
public, thenprotected, thenprivate, so a reader meets the interface first. - Prefer
protectedmember functions toprotecteddata when derived classes need controlled access. - Always write the inheritance specifier, and default to
public. - Use
friendsparingly and by name — chiefly for stream operators, which cannot be members. - Reach for composition instead of private inheritance; it says "uses a" more plainly.
- Return by value or
const&from accessors so callers cannot write through them. - Use a private nested type for helper structures to keep implementation details out of the header's public face.
Practice Exercises
- Collect the errors: Take the
DoorLockclass and, frommain, try to readlocked, callsetLocked, and assign tocode. Paste all three compiler messages into comments and note which access level each one names. - Private inheritance by accident: Write
class Sub : Base(no specifier) with a public base method, call that method on aSubobject, and record the error. Fix it withpublicand explain in one line whystruct Sub : Basewould have worked all along. - Friend versus accessor: Add a
friend std::ostream& operator<<(std::ostream&, const DoorLock&)that prints the lock state and failure count. Then write a second version that uses only the public methods instead, and say which you would ship and why.