Learn C++
#include "oopbasics/access_modifiers.hpp"

Access Modifiers in C++

//concept

public, protected, and private draw the class's trust boundary: public is the supported interface, private is implementation detail the compiler hides from outsiders, and protected opens up to derived classes while staying closed to everyone else. (class defaults to private, struct to public — the only difference between them.)

Encapsulation isn't secrecy for its own sake — it preserves the freedom to change internals without breaking callers. Expose behavior (methods), not data: a public getter can later compute, validate, or log, while a public field locks you into storage forever.

//how it works
1

public: the contract

Anyone may call public methods — this surface is what you document, test, and keep stable across versions.

2

private: the machinery

Outside code naming a private member fails to compile — fields, helpers, and invariants stay under the class's sole control.

3

protected: family access

Derived classes may use protected members while unrelated code still cannot — the extension point for frameworks.

4

Methods over fields

A private balance plus deposit()/getBalance() can enforce rules (no negative deposits); a public balance field never can.

//example
#include <iostream>
 
class Account {
double balance = 0.0;
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
double getBalance() const { return balance; }
};
 
int main() {
Account a;
a.deposit(50);
a.deposit(-99);
std::cout << a.getBalance() << std::endl;
return 0;
}
Output
50
1balance is private — only Account's own methods can touch it; main cannot name it at all.
2deposit(50) passes the positivity guard and adds; deposit(-99) fails it and changes nothing.
350 prints — the class invariant (never negative via deposits) held because data stayed private.
//use cases
Enforcing business rules (positive deposits, valid ranges) at the single choke point
Hiding representation so vector-to-list swaps never touch callers
Opening controlled extension with protected hooks in base classes
Reading access errors as the compiler pointing at encapsulation violations

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.