C++: Inheritance |Protected Inheritance Examples

Protected Inheritance Examples

Example:1

To access data elements of the base class from derived class members functions

//protected inheritance
//to access data elements of base class from derived class
//members functions
#include<iostream>
#include<conio.h>
using namespace std;
class abc
{
private:
	int a;
protected:
	int b;
public:
	int c;
};
class pqr:protected abc
{
private:
	int p;
protected:
	int q;
public:
	int r;
	void get();
	void disp();
};
void pqr::get()
{
	//a=10; //error
	b=20;
	c=30;
	p=40;
	q=50;
	r=60;
}
void pqr::disp()
{
  //cout<<"a= "<<a<<endl; //error
  cout<<"b = "<<b<<" c = "<<c<<endl;
  cout<<"p = "<<p<<" q = "<<q<<" r = "<<r<<endl;
}
int main()
{
	pqr p1;
	p1.get();
	p1.disp();
	getch();
	return(0);
}

Output:

b = 20 c = 30
p = 40 q = 50 r = 60

Example:2

To access data elements of the base class and derived class from the main function i.e. from outside the class

//protected inheritance
//to access data elements of base class and derived class
// from main function i.e. outside the class
#include<iostream>
#include<conio.h>
using namespace std;
class abc
{
private:
	int a;
protected:
	int b;
public:
	int c;
};
class pqr:protected abc
{
private:
	int p;
protected:
	int q;
public:
	int r;
};
int main()
{
	pqr p1;
  	//p1.r=60;//valid
	//or
	cout<<"Enter value of r "; //valid
	cin>>p1.r;       //valid
	cout<<"r = "<<p1.r<<endl;
  	getch();
  	return(0);
}

Output:

Enter value of r 500
r = 500