What are access specifiers in C++?
| Specifier | Who can use it |
|---|---|
| public | Everyone |
| protected | The class and derived classes |
| private | Only 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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |