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 Class2class Wumpus : public Monster {3 public:4 ...5 void SelfDestruct() {6 cout << "GG, Wumpus is outta here" << endl;7 this->hearts = 0; // ERROR8 }910 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 Class2class Monster {3 public:4 void setHealth(int hearts) {5 this->hearts = hearts;6 }78 int getHealth() {9 return this->hearts;10 }1112 protected:13 int hearts;14}151617// Derived Class18class Wumpus : public Monster {19 public:20 void Hide() {21 cout << "Shhhhhhh" << endl;22 this->isVisible = false;23 }2425 void Appear() {26 cout << "ARGHHARHGHHHH" << endl;27 this->isVisible = true;28 }2930 void SelfDestruct() {31 cout << "GG, Wumpus is outta here" << endl;32 this->hearts = 0; // No Error33 }3435 private:36 bool isVisible;37}3839int main() {40 Monster base;41 Wumpus derived;4243 derived.SelfDestruct() // No Error4445 base.hearts = base.hearts + 1; // Error, trying to modify protected member4647 cout << "Monster health: " << base.hearts << endl; // Also throws an error48 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
- C++ Inheritance: Subclass Definition (Pt. 1)
- C++ Inheritance: Inheritance Access Levels (Pt. 3)
- C++ Inheritance: Overriding Base Class Methods (Pt. 4)
- C++ Inheritance: Polymorphism (Pt. 5)
Written by Riley Miller, follow me on Twitter 🐦