Access specifiers enforce encapsulation: public, protected, and private control who can reach members—like Java but with struct defaulting to public.
Encapsulation pattern
class BankAccount {
public:
void deposit(int cents) { balance_ += cents; }
int balance() const { return balance_; }
private:
int balance_ = 0;
};
Keep data private; expose small, validated public interfaces.
Important interview questions and answers
- Q: friend keyword?
A: Grants specific functions/classes access to private members—use sparingly. - Q: protected vs private?
A:protectedvisible to derived classes;privateonly within the class (and friends).
Self-check
- Default access in struct vs class?
- Why keep fields private?
Tip: struct defaults to public; class defaults to private—choose class for types with invariants.
Interview prep
- private members?
Accessible only within the class (and friends)—enforces encapsulation.
- friend functions?
Granted access to private members—use sparingly for tightly coupled helpers.