0
0
CppConceptBeginner · 3 min read

What is protected keyword in C++: Explanation and Example

In C++, the protected keyword is an access specifier that allows class members to be accessible within the class itself and by its derived (child) classes, but not from outside these classes. It is like a middle ground between private and public access levels.
⚙️

How It Works

Think of a class as a house with rooms. The protected keyword marks certain rooms that only the house owner and their family (derived classes) can enter, but visitors (outside code) cannot. This means that members marked as protected are hidden from the outside world but shared with child classes.

This helps keep important details safe while still allowing child classes to use or change them. It is more open than private, which only the house owner can access, but more restricted than public, which anyone can enter.

💻

Example

This example shows a base class with a protected member and a derived class accessing it.
cpp
#include <iostream>

class Animal {
protected:
    int age;
public:
    Animal(int a) : age(a) {}
};

class Dog : public Animal {
public:
    Dog(int a) : Animal(a) {}
    int getAge() {
        return age;  // Accessing protected member from base class
    }
};

int main() {
    Dog myDog(5);
    std::cout << "Dog age: " << myDog.getAge() << std::endl;
    // std::cout << myDog.age; // Error: 'age' is protected
    return 0;
}
Output
Dog age: 5
🎯

When to Use

Use protected when you want to hide class details from the outside world but still allow child classes to access or modify them. This is useful in object-oriented design where you build a base class with common features and let derived classes extend or customize those features.

For example, in a game, a base class Character might have protected health points that only specific character types can change. This keeps health safe from outside code but flexible for child classes.

Key Points

  • Protected members are accessible in the class and its derived classes.
  • They are not accessible from outside these classes.
  • It provides controlled access, balancing encapsulation and inheritance.
  • Useful for sharing data or functions with child classes without exposing them publicly.

Key Takeaways

The protected keyword allows access to class members only within the class and its derived classes.
It hides members from outside code but shares them with child classes for flexibility.
Use protected to safely share data or behavior in inheritance hierarchies.
Protected is more open than private but more restricted than public access.