What are access specifiers in C++?

SpecifierWho can use it
publicEveryone
protectedThe class and derived classes
privateOnly the class (and friends)
class A {
private:
    int secret = 1;
public:
    int open = 2;
};

int main() {
    A a;
    int x = a.open;
    int y = a.secret;
}
Output

Private.cpp: In function 'int main()':
Private.cpp:11:15: error: 'int A::secret' is private within this context
11 | int y = a.secret;
| ^~~~~~
Private.cpp:3:9: note: declared private here
3 | int secret = 1;
| ^~~~~~
Private.cpp:10:9: warning: unused variable 'x' [-Wunused-variable]
10 | int x = a.open;
| ^
Private.cpp:11:9: warning: unused variable 'y' [-Wunused-variable]
11 | int y = a.secret;
| ^

See Access Specifiers and Encapsulation.


Learn more about the similar topics:
Tutorials
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?