`private` — C++ Keyword

`private` — C++ Keyword

The private keyword in C++: restricts member access to within the class itself.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

private

Declares that members are accessible only within the class (and its friend declarations). The default access level for class types.

Syntax

class Name {
private:
    // only accessible inside this class and friends
};

Example

#include <print>

class BankAccount {
public:
    explicit BankAccount(double initial) : balance_(initial) {}

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

    double balance() const { return balance_; }

private:
    double balance_;   // external code cannot modify this directly
};

int main() {
    BankAccount acct{100.0};
    acct.deposit(50.0);
    // acct.balance_ = 999.0;   // error: private
    std::println("{}", acct.balance());   // 150
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}