Access Modifiers in C++
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.
public: the contract
Anyone may call public methods — this surface is what you document, test, and keep stable across versions.
private: the machinery
Outside code naming a private member fails to compile — fields, helpers, and invariants stay under the class's sole control.
protected: family access
Derived classes may use protected members while unrelated code still cannot — the extension point for frameworks.
Methods over fields
A private balance plus deposit()/getBalance() can enforce rules (no negative deposits); a public balance field never can.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.