Skip to main content
Engineering LibreTexts

1.12: Protected Access Specifier

  • Page ID
    34644
  •  Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
    Example:

    // C++ program to demonstrate 
    // protected access modifier    
    #include <bits/stdc++.h> 
    using namespace std;
    // base class 
    class Parent 
    { 
        // protected data members 
        protected: 
            int id_protected; 
    };
    
    // sub class or derived class 
    class Child : public Parent 
    { 
        public: 
            void setId(int id) 
            { 
                // Child class is able to access the inherited 
                // protected data members of base class 
                id_protected = id; 
            } 
    
            void displayId() 
            { 
                cout << "id_protected is: " << id_protected << endl; 
            } 
    };
    
    // main function 
    int main() 
    
    { 
            Child obj1; 
    
            // member function of the derived class can 
            // access the protected data members of the base class 
            obj1.setId(81); 
            obj1.displayId(); 
            return 0; 
    } 

    Output:

    id_protected is: 81

    Adapted from:
    "C++ Classes and Objects" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY 4.0

    • Was this article helpful?