C++ Access Specifiers

In C++, the access to data members and members functions are regulated using access specifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, we should minimize access whenever possible.

Actually there are three access specifiers in C++, namely public, private and protected. C++ uses these access specifiers to help us set the level of access we want for classes as well as the data members, members functions and constructors in our classes. 

 

These access specifiers are described below.

1. public access specifier :

The data members, members functions and constructors declared public within a class are visible to any class in the C++ program.

2. private access specifier :

The data members or members functions declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all data members private and provide public member functions for accessing them.

3. protected access specifier :

The data members and members functions declared protected in a base class can be accessed only by the derived classes. 

 

Access Specifier Example

The following example shows the differences between public and private data members.

Here, the public data members can be accessed and modified from outside the class using the object; but not the private data members.

If we try to access a private data member using the object, a compilation error will occur. So, we put a single-line comment symbol (//) beside the code statement. See the program code below .

#include <iostream>
using namespace std;

class Test {
private:
int data_pvt; //private data member

public:
int data_pub; //public data member
};

int main() {
Test obj; //creating object

//obj.data_pvt = 10; // private : Not allowed by C++ compiler

obj.data_pub = 20; // public : Allowed by C++ compiler

cout << "data_pub: " << obj.data_pub;

return 0;
}

Output:

data_pub: 20

Note: It is possible to access private data members of a class using a public member function inside the same class.