What is Protected Access Specifier in C++


This C++ program demonstrates the use of the protected access specifier in class inheritance.

  • In this program, there are two classes - class A and class B. Class A has a single protected data member x. Class B publicly inherits from class A, so it can access the protected member x.
  • The program creates an object of class B, calls the getDetails() function to set the value of x, and then displays the value of x using the display() function.
  • When we use the protected access specifier, the derived class can access the protected members of the base class, but these members are not accessible outside the class hierarchy.
  • In this program, since x is a protected member of class A, it is accessible in the derived class B but not outside the class hierarchy. This helps in encapsulating the data and providing better security and flexibility to the program.

Source Code

#include<iostream>
using namespace std;
//Protected Access Specifier in C++
class A
{
   protected:
       int x;
};
 
class B:public A
{
public:
    void getDetails()
    {
        cout<<"\nEnter The Value of X : ";
        cin>>x;
    }
    void display()
    {
        cout<<"X : "<<x;
    }
};
int main()
{
    B o;
    o.getDetails();
    o.display();
    return 0;
}
 

Output

Enter The Value of X : 23
X : 23
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples