Protected Access Specifier in C++

 


1️⃣ What is the protected Access Specifier?

In C++, the protected access specifier is used in classes to restrict access to members. It allows:

  • Access within the same class.
  • Access in derived (child) classes.
  • Not accessible outside the class (unlike public).

2️⃣ Syntax of protected Access Specifier

class Base {
protected: 
    int protectedVar;  // Accessible in derived class
};

3️⃣ Example: Using protected in Inheritance

#include <iostream>
using namespace std;

// Base Class
class Parent {
protected:
    int protectedVar; // Protected member

public:
    Parent(int val) {
        protectedVar = val;
    }

    void showValue() {
        cout << "Protected Variable: " << protectedVar << endl;
    }
};

// Derived Class
class Child : public Parent {
public:
    Child(int val) : Parent(val) {}

    void modifyValue(int newVal) {
        protectedVar = newVal;  // Allowed because it is protected
    }
};

int main() {
    Child obj(100);
    obj.showValue();  // ✅ Allowed: Public function of Base
    obj.modifyValue(200);
    obj.showValue();
    
    // obj.protectedVar = 300; ❌ ERROR: Cannot access protected member outside the class
    return 0;
}

🔹 Output

Protected Variable: 100
Protected Variable: 200

4️⃣ Key Differences: private vs protected vs public

Access Modifier Accessible in Same Class Accessible in Derived Class Accessible Outside Class
private ✅ Yes ❌ No ❌ No
protected ✅ Yes ✅ Yes ❌ No
public ✅ Yes ✅ Yes ✅ Yes

5️⃣ When to Use protected?

🔹 When you want derived classes to access a member, but not external code.
🔹 Useful in inheritance to share data between base and derived classes.
🔹 Helps enforce encapsulation while allowing subclass flexibility.

Would you like a real-world example using protected? 🚀

Post a Comment

0 Comments