Protected Access specifier in C++:
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 Base
{
private:
int private_mem;
void private_memfunc()
{
cout<<"private_memfunc";
}
protected:
int protected_mem;
void protected_memfunc()
{
cout<<"protected_memfunc";
}
public:
int public_mem;
void public_memfunc()
{
cout<<"public_memfunc";
}
};
class Derv:public Base
{
public:
void set_base_members()
{
// private_mem=1; /*error: 'int Base::private_mem' is private*/
protected_mem=2;
public_mem=3;
// private_memfunc(); /*error: 'void Base::private_memfunc()' is private*/
protected_memfunc();
public_memfunc();
}
};
int main()
{
Derv d;
d.set_base_members();
// d.private_mem=10; /*error: 'int Base::private_mem' is private*/
// d.protected_mem=20; /*error: 'int Base::protected_mem' is protected */
d.public_mem=30;
// d.private_memfunc(); /*error: 'void Base::private_memfunc()' is private*/
// d.protected_memfunc(); /*error: 'void Base::protected_memfunc()' is protected */
d.public_memfunc();
}
