Â
Access Specifiers in C++ :-Â Access specifiers define how the members (attributes and methods) of a class can be accessed. The keywords in C++ such as public, private and protected are called as access specifiers.
1. public :-Â members are accessible 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.
Example:-
public
#include<iostream> using namespace std; class MyClass { public: // Public access specifier int x=100; // Public member of class }; int main() { MyClass myObj; cout<<myObj.x; // Allowed (public) return 0; }
Output
private
#include<iostream> using namespace std; class MyClass { private: // Private access specifier int x=100; // Private attribute }; int main() { MyClass myObj; cout<<myObj.x; // Allowed (public) return 0; }
Output
protected
#include<iostream> using namespace std; class MyClass { protected: // Protected access specifier int x=100; // Protected attribute }; int main() { MyClass myObj; cout<<myObj.x; // Allowed (public) return 0; }
Output
From above examples we come to know that, private and protected members of a class cannot be accessed out-side of the class.
Private members can only be accessed by the member functions or member variables of that class.
In case of Private members, they can only be accessed by inherited class of Parent class, this thing we will come to know while studying the concept of inheritance.
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP