Access Specifiers in C++
Access specifiers in C++ are basically used in OOPs concepts. These are used, when we create a class. Inside the class, we specify the accessibility of the member variables and member functions by the using of access specifiers. They set the range for the usage of the variable and the functions of a particular class. Access specifiers are used for data hiding purposes also.
There are three access specifiers Private, Protected and Public that are used in C++.
Syntax:
{
Access_specifier:
variable_name;
function_name();
};
Public:
Public access specifier is used in that scenario when we want to access the member functions and variables outside of the class without any restrictions. The data members and member functions of a class declared as public are available to everyone and other classes can also access them. That's why the constructor and destructor are always declared as public. The public members of a class are accessible from everywhere in the program using the dot operator (.) which is called a direct member access operator along with the object of the same class.
The number is: 10
Private:
The data members and member functions of a class declared as private are accessible only by the inside functions of the class and are restricted to be accessed directly by any object or function outside the class. It prevents member variables and member functions to access directly from the outside of the class. The private data members of a class can be accessed using the member functions of the class or the friend functions.
Error occure!
The number is: 20
Protected:
Protected access specifierknown is similar to that of private access specifier, the difference is that the class member declared as Protected cannot be accessed outside the class however they are accessible by any derived class or subclass of that class known as inheritance. We will discuss about it in the next chapter.
The main difference between private and protected is that protected inheritance allows continued access to base class members whereas private inheritance prohibits the access of those members.