Thuta Learning
AdvancedProgrammingbeginner

Access Specifiers

Relax. We'll talk through this in plain words — no textbook voice.

An access specifier determines where a class member can be accessed from. public members can be accessed from outside the class, while private members can only be accessed by methods inside the class. This protects data from being changed directly when it shouldn't be.

cpp
#include <iostream>
using namespace std;

class BankAccount {
  private:
    double balance;

  public:
    BankAccount(double startBalance) {
        balance = startBalance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account(100);
    account.deposit(50);
    cout << account.getBalance();
    return 0;
}

balance is kept private, so it can't be changed directly from outside. To make a deposit, you have to go through the deposit() method, which lets you check whether the amount is valid.

You should see
150

Info

This is called encapsulation — keeping data contained within the class and exposing safe access only through public methods.

Easy traps

  • Making every attribute public is easy at first, but it invites bugs as a project grows. Keep sensitive data private.
Access Specifiers | Thuta Learning