Wednesday 8 April 2015

Protected Access Specifier

We have seen how to increase the capabilities of an existing class without modifying it. We have also seen that a private member of a base class cannot be inherited and therefore it is not available for the derived class directly. What do we do if the private data needs to be inherited by a derived class. This can be accomplished by modifying the visibility limit of the private member by making public.


C++ provides a third visibility modifier, protected, which serve a limited purpose in inheritance. A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. It cannot be accessed by the function outside these two classes.


When a protected member is inherited in pubic mode, it becomes protected in the derived class too, and therefore is accessible by the member functions of the derived class. It is also ready for further inheritance. A protected member, inherited in the private mode derivation, become private in the derived class. Although it is available to the member functions of the derived class, it is not available for further inheritance.


Now let us review the control to the private and protected data, the member functions of a derived class can directly access only the prtected data.


Sample Program

#include <iostream.h>
class one
{
protected:
int rno;
char name[10];
public:
void showname(void)
{
cout<<”Student Number is “<<rno<<endl;
cout<<”Student Name is”<<name<<endl;
}
};
class two:public one
{
float tot;
public:
void setdata(void)
{
cout<<”Enter the Rno, name and total\n”;
cin>>rno>>name>>tot;
}
void showtot(void)
{
cout<<”Total mark is”<<tot;
}
};
void main()
{
two D;
D.setdata();
D.showname();
D.showtot();
}

No comments:

Post a Comment