C++: Inheritance|Public Inheritance Examples

Public Inheritance Examples

Example:1

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

//public 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:public 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 main function i.e. from outside the class

//public 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:public abc
{
private:
	int p;
protected:
	int q;
public:
	int r;
};
int main()
{
  pqr p1;
  //p1.abc::b=20; //error
  p1.abc::c=30;
  p1.r=60;
  cout<<"c = "<<p1.abc::c<<endl;
  cout<<"r = "<<p1.r<<endl;
  getch();
  return(0);
}

Output:

c = 30
r = 60