Access control in privately derived class
From a privately derived class, public and protected members of the base class become private members of the derived class. Hence it is not possible to access the derived members using the object of the derived class.The Derived members are invoked by calling it from the publicly defined members
#include<iostream>
#include<string>
using namespace std;
class Employee
{
private:
char name[50];
int code;
public:
void getinfo();
void dispinfo();
};
class staff: private Employee
{
private:
int ex;
public:
void getdata();
void display();
};
void Employee::getinfo()
{
cout<<"Name:";
gets(name);
cout<<"Code:";
cin>>code;
}
void Employee::dispinfo()
{
cout<<"Name:"<<name<<endl;
cout<<"Code:"<<code<<endl;
}
void staff::getdata()
{
getinfo(); //invoked inside
cout<<"Experience:";
cin>>ex;
}
void staff::display()
{
dispinfo(); //member function called inside another member function
cout<<"Experience:"<<ex<<" Years"<<endl;
}
int main()
{
staff s;
cout<<"Enter data"<<endl;
s.getdata();
cout<<endl<<endl<<"\tDisplay Data"<<endl;
s.display();
return 0;
}
Enter data
Name: BALAMURUGAN
Code: 1201
Experience: 30
Display Data
Name: BALAMURUGAN
Code: 1201
Experience: 30 Years
If you look at the output of publicly derived class and privately derived class are same the way of defining is different. This is because the private members of the derived class cannot be accessed by its object. In the above program since staff is privately derived getinfo() and dispinfo() become private to class “staff”. To access both the member function they are invoked inside the publ;ic member functions getdata() and display() respectively.
Member functions can access the private members
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.