In C++ classes, members of a superclass (base class) are inherited by its subclass (derived class) if they are public. When the data members are private, they are not accessible in subclass. But what about inheritance of members in subclass and restricting their access from outside directly?
Need for protected access specifier in C++:
Protected access specifier overcomes this problem. It allows inheriting of members in subclass and their subclasses and so on. Members with protected access specifier of a superclass allows its subclasses and their child classes to access them of directly as if it belonged to their own class and at the same time makes it as private restricting other classes to inherit them.
Sample code explaining how and when to use protected access specifiers in C++:
class Derv:public Base
// private_mem=1; /*error: 'int Base::private_mem' is private*/
// private_memfunc(); /*error: 'void Base::private_memfunc()' is private*/
// d.private_mem=10; /*error: 'int Base::private_mem' is private*/
// d.protected_mem=20; /*error: 'int Base::protected_mem' is protected */
// d.private_memfunc(); /*error: 'void Base::private_memfunc()' is private*/
// d.protected_memfunc(); /*error: 'void Base::protected_memfunc()' is protected */