Access specifiers are used for data hiding which is the one of the most important features of OOP. This prevents the functions from the direct access of internal variables.
Those access specifiers to the class members are labelled as public, private, protected sections within class.
A single class can have public, private, protected sections. And each section remains in effect until either another section starts or closing bracket of class is seen. The default access specifier for members and classes is private.
If a member is specified as a public member than we can access it from anywhere in that code. We can set, get, modify the value of those members without calling any function.
In above code we can see that variables and functions are declared as private members. So we are able to set value of variable ‘ele’ in main() by 2 methods — using ‘setValue’ function and by directly setting value of ‘ele’.
If a member variable or function is specified as a private member than we cannot access or view (get) from outside of the class. Only the class in which it is defined or a friend class can access those members variable or function.
In above code we can see that we have declare one variable as private member, one variable as public member and two functions as public members. For setting the value of ‘priEle’ variable, we are calling ‘setValue’ function, if we try to set value of ‘priEle’ variable directly then we will face an ERROR.
Whenever we define a member or a function, by default they will be private members of that class.
Here ‘obj1’ is not specified by any access specifier, so it will be set as a private member; while ‘obj2’ is specified by public specifier, so it will be set as public member.
Usually, member variables are declared as private members and member functions are declared as public members. This is done so no one can directly alter the values of variables.
Protected member variable or function is very similar to private member variable or function, the only difference is that protected members can be accessed by derived classes (child class/sub class).
In above code we can see that there are two classes declared, namely ‘Parent’ and ‘Child’, here ‘Child’ class is a derived class of ‘Parent’ class. In ‘Parent’ class we have declared ‘pEle’ as protected variable and in ‘Child’ class we have declared two functions. Using the functions of ‘Child’ class we can set the value of ‘pEle’ (which is declared in ‘Parent’ class).
Now you have all the information about access specifiers, how to declare, how they work, and how to use them as per your needs. Hope you will find this helpful.