Access Specifiers in C++ (Private, Public and Protected)
Written by
Access specifiers in C++
We have seen about the access specifiers like private and public, but what are they and actually what is their significance? We will try and find answers to all these types of questions in this chapter.
Data hiding as we all know, is an important concept of the Object-Oriented Programming. This concept is employed with the help of the access specifiers namely: public, private and protected in a class.
Public Access Specifier:
The public access specifier ensures that the members are accessible anywhere in the program code.
Any member can be declared public, in a class using the public keyword.
Private Access Specifier:
A private member variable or function cannot be accessed, or even viewed from outside the class.
Only the class and friend functions can access private members. By default all the members of a class are private. However, we can declare any member as private using the private keyword.
Protected Access Specifier:
A protected member variable or function is very similar to a private member but it provides an additional benefit that the protected members can be accessed in child classes which are called derived classes.
That is the protected members are inheritable, just like the public members. We can declare any member as protected using the protected keyword.
Thus, we can easily see how, the concept of data hiding is being implemented with the help of the access specifiers in C++. Now, let us take a look at the code which makes use of these specifiers.
#include <iostream.h>
class Box {
public:
int length;
void setWidth( int wid );
int getWidth( void );
private:
int width;
};
// Member functions definitions
int Box::getWidth(void) {
return width ;
}
void Box::setWidth( int wid ) {
width = wid;
}
// Main function for the program
int main() {
Box box;
box.length = 10.0; // length is public, thus it is accessible
cout << "Length of box : " << box.length <<endl;
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function, which is public to set width.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
}