Private Access Modifiers
Published Feb 5, 2025
Contribute to Docs
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
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:
#include <iostream>class Secret {private:// Private member variableint secretVar;public:// Public member function to set the private variablevoid setSecret(int value) {secretVar = value;}// Public member function to reveal the private variableint revealSecret() {return secretVar;}};int main() {Secret mySecret;// Throws an error// mySecret.secretVar = 10;// Error: secretVar is private// Use public function to set the valuemySecret.setSecret(10);// Use public function to get the valuestd::cout << mySecret.revealSecret();return 0;}
The above code will give the following output:
10
Codebyte Example
Run the following codebyte example to understand how the private access modifiers work:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours