C++ Language



Admission Enquiry Form

  

Use of Protected Access Specifier in C++




Use of Protected Access Specifier in C++

Understanding the concept of Protected Access Specifier in C++ Inheritance

We know that a private member of a base class cannot be inherited and therefore it is not available for the derived class directly.

What should we do if the private data needs to be inherited by a derived class?

This can be done by modifying the visibility limit of the private member by making it public. But,by using public it will be accessible to all the other functions of the program also.
But, we want that it should be accessed only by derived class.So, then in C++ there is third visibility mode i.e. protected which serves a limited purpose in inheritance. A member declared as protected is accessible by same class member functions and any class immediately derived from it. It cannot be accessed by the function outside these two classes.
For Example:

class Test
{
private:   //optional
...        //visible to the member functions
...        //within its class

      protected:
...        //visible to the member functions
...        //of its own and derived class
public:
...        //visible to all functions
...        //in the program
};




Use of Protected Data Member in Derived Class

#include<iostream>
using namespace std;
class Base
{
protected:
int x;
public:
void show()
{
x=100;
cout<<"\nBase class show() "<<x;
}
};//end of Base class
class Derived : public Base
{
public:
void display()
{
x=500;//protected data of base class
cout<<"\nDerived class Display() "<<x;
}
};//end of class

int main()
{
Derived d;
d.show();
d.display();
}




Use of Protected in Derived Class

we can also use the keyword protected as visibility mode in the defining of the derived class. Such inheritance using the visibility mode protected is known as protected inheritance.

In protected inheritance, public members of base class become protected in derived class as also the protected members of the base class become protected in the derived class.


Example:

#include<iostream>
using namespace std;
class Base
{
public:
void show()
{
cout<<"\nBase class show() ";
}
};//end of Base class
class Derived :protected Base //protected inheritance of base class
{
public:
void display()
{
show();//it is protected in derived
// can not be accessed by derived class
cout<<"\nDerived class Display() ";
}
};//end of class

int main()
{
Derived d;
//d.show();
d.display();
}