Access Specifiers
The public keyword that occurs in all our class examples is our access specifier. Access specifiers defines the accessibility of classes, methods, and other members.
There are three kinds of access specifiers in C++
1) Public : members can be accessed (or viewed) from outside the class
2) Private : members cannot be accessed (or viewed) from outside the class
3) Protected : members cannot be accessed from outside the class, however, they can be accessed in inherited classes. (We can define inherited classes as those which inherit attributes and methods from one class to another.)
We have already looked at examples of public. We will look at the private access specifier with an example:
Example:
#include <iostream>
using namespace std;
class My_Class {
public: // Public access specifier
int a; // Public attribute
private: // Private access specifier
int b; // Private attribute
};
int main() {
My_Class my_Obj;
my_Obj.a = 16; // Able to view it(a is public)
my_Obj.b = 2002; // Not allowed to view it (b is private)
return 0;
}
Output:
Error
main.cpp: In function ‘int main()’:
main.cpp:19:10: error: ‘int My_Class::b’ is private within this context
my_Obj.b = 2002; // Not allowed to view it (b is private)
^
main.cpp:10:9: note: declared private here
int b; // Private attribute
^