Riley Miller

C++ Inheritance: Protected Member Access (Pt. 2)

July 06, 2020

Without inheritance, most classes typically use either public or private to specify the access level of their class members. However, if a derived class tried to interact with a private member of the base class, the compiler would throw an error complaining about a private member being accessed in the derived class. Example:

1// Derived Class
2class Wumpus : public Monster {
3 public:
4 ...
5 void SelfDestruct() {
6 cout << "GG, Wumpus is outta here" << endl;
7 this->hearts = 0; // ERROR
8 }
9
10 private:
11 bool isVisible;
12}
13

Since hearts is specified as a private member on the base class, this member cannot be accessed directly by any of the methods of a derived class.

This is where the protected access level becomes useful. The protected member access level specifies that any derived class can access the protected member but nothing else. Example:

1// The Base Class
2class Monster {
3 public:
4 void setHealth(int hearts) {
5 this->hearts = hearts;
6 }
7
8 int getHealth() {
9 return this->hearts;
10 }
11
12 protected:
13 int hearts;
14}
15
16
17// Derived Class
18class Wumpus : public Monster {
19 public:
20 void Hide() {
21 cout << "Shhhhhhh" << endl;
22 this->isVisible = false;
23 }
24
25 void Appear() {
26 cout << "ARGHHARHGHHHH" << endl;
27 this->isVisible = true;
28 }
29
30 void SelfDestruct() {
31 cout << "GG, Wumpus is outta here" << endl;
32 this->hearts = 0; // No Error
33 }
34
35 private:
36 bool isVisible;
37}
38
39int main() {
40 Monster base;
41 Wumpus derived;
42
43 derived.SelfDestruct() // No Error
44
45 base.hearts = base.hearts + 1; // Error, trying to modify protected member
46
47 cout << "Monster health: " << base.hearts << endl; // Also throws an error
48 return 0;
49}
50

After moving int hearts from private to protected in the base class, Monster, the derived class, Wumpus, can now interact with the attribute directly without making the compiler unhappy.

However, as shown when trying to access and modify the protected attribute in main(), the compiler gets unhappy since only derived classes are allowed to interact with protected members of the base class.

C++ Inheritance Articles


Written by Riley Miller, follow me on Twitter 🐦

//