# C++: error: 'int X::secret' is private within this context

**Code:** `is private within this context` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

Code outside the class tried to use a private (or protected) member.

## Meaning

Members of a `class` are private by default; a `struct` defaults to public. Access is checked by the name's declaration, not by the object, so even a getter named differently is the fix. Friends and member functions of the same class are exempt.

## Common causes

- Accessing a private data member from `main` or another class
- Inheriting privately (the default for `class D : B`) and converting to the base
- Forgetting `public:` after the first member of a class
- Protected member accessed through a base-class object instead of `this`

## Quick fix

1. Add a public getter/setter or a public method that does the work
2. Change to `struct` or add `public:` if the member should be public
3. Declare `friend` only for tightly coupled helpers

## Detailed fix by platform

### C++

1. Expose behaviour, not data: `int secret() const { return secret_; }`
2. Use `class D : public B` when you want an is-a relationship

## Code examples

### Access control

```cpp
class Account {
    int balance_ = 0;                     // private by default
public:
    int balance() const { return balance_; }
    void deposit(int n) { balance_ += n; }
};

int main() {
    Account a;
    // a.balance_ = 5;                    // error: 'int Account::balance_' is private within this context
    a.deposit(5);
    return a.balance();
}
```

## How to diagnose

1. **Access** — Is the member private, protected or public?
2. **Inheritance** — class or struct, public or private?
3. **Caller** — Is the code inside the class or a friend?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/private-within-this-context)
