All Courses
OOP: ACCESS SPECIFIERS

`private` Access Specifier

private means a member can be used only inside the class itself, plus any declared friends.

For OOP, private data is the default good habit.

Why Use private?

Private data protects object state.

If outside code can directly change data, the object cannot enforce its own rules.

Example problem:

// account.balance = -5000; // this should not be allowed

Example

#include <iostream>
#include <string>

class BankAccount {
private:
    std::string accountNumber;
    double balance;

public:
    BankAccount(const std::string& number, double initialBalance)
        : accountNumber(number), balance(initialBalance) {}

    void displayBalance() const {
        std::cout << accountNumber << ": $" << balance << '\n';
    }
};

int main() {
    BankAccount account("12345", 500.0);
    account.displayBalance();

    // account.balance = 1000.0; // error: balance is private
}

Who Can Access Private Members?

Allowed:

  • member functions of the same class
  • friend functions/classes explicitly declared by the class

Not allowed:

  • main()
  • unrelated classes
  • derived classes directly

Private Does Not Mean Unimportant

Private data is often the most important part of the object. It is private because it must be protected.

Viva Answer

private members can be accessed only by the class's own member functions and declared friends. We use private to protect object state and force outside code to use safe public methods.

Quick Check

  • Can main() access private data directly?
  • Can a member function access private data?
  • Why should balance be private?
  • Can derived classes directly access private base members?