The protected Keyword in C++

A protected member of a class can be accessed from a derived class.

So far, you have used the private and public keywords to specify whether data fields and functions can be accessed from outside the class. Private members can be accessed only from inside the class or from friend functions and friend classes, and public members can be accessed from any other classes.

Often it is desirable to allow derived classes to access data fields or functions defined in the base class but not allow nonderived classes to do so. For this purpose, you can use the protected keyword. A protected data field or a protected function in a base class can be accessed in its derived classes.

The keywords private, protected, and public are known as visibility or accessibility keywords because they specify how class and class members are accessed. Their visibility increases in this order:

Listing 15.12 demonstrates the use of protected keywords.

Listing 15.12 VisibilityDemo.cpp

1 #include <iostream>
2
using namespace std;
3
4
class B
5 {
6   
public:
7   
int i;
8
9   
protected:
10   
int j;
11
12   
private:
13   
int k;
14 };
15
16
class A: public B
17 {
18   
public:
19   
void display() const
20    {
21       cout << i << endl;
// Fine, can access it
22       cout << j << endl; // Fine, can access it
23       cout << k << endl; // Wrong, cannot access it
24    }
25 };
26
27
int main()
28 {
29    A a;
30    cout << a.i << endl;
// Fine, can access it
31    cout << a.j << endl; // Wrong, cannot access it
32    cout << a.k << endl; // Wrong, cannot access it
33
34   
return 0;
35 }

Since A is derived from B and j is protected, j can be accessed from class A in line 22.

Since k is private, k cannot be accessed from class A.

Since i is public, i can be accessed from a.i in line 30. Since j and k are not public, they cannot be accessed from the object a in lines 31-32.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *