Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created the file for private access modifier #6031

Merged
merged 6 commits into from
Feb 5, 2025
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions content/cpp/concepts/access-modifiers/terms/private/private.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
Title: 'Private Access Modifiers'
Description: 'Specifies that class members are only accessible from within the class itself.'
Subjects:
- 'Computer Science'
Tags:
- 'Classes'
- 'Access Modifiers'
CatalogContent:
- 'learn-c-plus-plus'
- 'paths/computer-science'
---

In C++, the **`private`** keyword keeps class members hidden. This means that only the methods within the same class can access these members. Objects of the class and functions outside the class **cannot** access them directly.

## Syntax

```pseudo
class ClassName {
private:
// Private members
};
```

## Example

In the example below, attempting to directly access the `private` data member `secretVar` from outside the class would result in a compilation error:

```cpp
#include <iostream>

class Secret {
private:
// Private member variable
int secretVar;

public:
// Public member function to set the private variable
void setSecret(int value) {
secretVar = value;
}

// Public member function to reveal the private variable
int revealSecret() {
return secretVar;
}
};

int main() {
Secret mySecret;

// Throws an error
// mySecret.secretVar = 10;
// Error: secretVar is private

// Use public function to set the value
mySecret.setSecret(10);
// Use public function to get the value
std::cout << mySecret.revealSecret();

return 0;
}
```

The above code will give the following output:

```shell
10
```
mamtawardhani marked this conversation as resolved.
Show resolved Hide resolved
Loading