C++ ยท Chapter 34 of 49

C++ Access Specifiers

Access specifiers `public`, `private`, and `protected` control which parts of a program can access a class's members. `public` members are accessible from anywhere, `private` only from within the class, and `protected` from the class and its derived classes.

Using private members with public getter/setter methods is a common pattern that protects internal data from being set to invalid values directly.

public vs private

Public members form the class's external interface. Private members are implementation details hidden from outside code, accessible only through the class's own methods.

protected

protected acts like private but also allows derived (child) classes to access the member directly, which is useful when designing an inheritance hierarchy.

Example 1 (cpp)
class Account {
private:
    double balance = 0;
public:
    void deposit(double amt) { balance += amt; }
    double getBalance() { return balance; }
};
int main() {
    Account a;
    a.deposit(100);
    std::cout << a.getBalance();
}
Output
100

balance is private and only reachable through public deposit()/getBalance() methods.

Key points

  • public: accessible from anywhere.
  • private: accessible only within the class.
  • protected: accessible within the class and its subclasses.
  • Getters/setters expose controlled access to private data.
๐Ÿ’ก Note: Defaulting to private members and exposing only what's needed publicly is a core encapsulation practice.

๐Ÿ“ Quick Quiz

1. Which access level allows derived classes but not outside code?

2. Private members can be accessed:

3. A getter method is typically: