Online Tutorials & Training Materials | STechies.com
Register Login

Hybrid Inheritance Sample Program in C++

|| 0

Hybrid Inheritance Sample Program in C++
Stechies

What is Hybrid or Multipath Inheritance?

Hybrid inheritance, also called multipath inheritance, is the process of deriving a class using more than one level or more than one mode of inheritance. For example, a class ‘marks’ is derived from class ‘stu’ by single level inheritance. Another class ‘sports’ is created and a class ‘result’ is derived from both ‘marks’ and ‘sports’ classes by multiple inheritances. The class ‘result’ is derived using hybrid inheritance. In another example, two classes ‘d1’ and ‘d2’ are derived from base class ‘B’ using hierarchical inheritance. Another class ‘D’ is derived from classes 'd1’ and ‘d2’ using multiple inheritances. The class ‘D’ is now derived using hybrid inheritance.

C++ Multipath Inheritance

Sample program for Hybrid Inheritance:

#include<iostream.h>
#include<conio.h>
class stu{ //First base Class//
	int id;
	char name[20];
	public: //If not declared, data members are by default defined as private//

	void getstu(){
		cout << "Enter stuid, name";
		cin >> id >> name;
	}
};

class marks: public stu{//derived class//
	protected: //without this command, data members will not be available next//
	int m, p, c;// without ‘protected:’ command, m1, m2, & m3 are private members//
	public:
	void getmarks(){
		cout << "Enter 3 subject marks:";
		cin >> m >> p >> c;
	}
};

class sports{//Second base class//
	protected:
	int spmarks;
	public:
	void getsports(){
		cout << "Enter sports marks:";
		cin >> spmarks;
	}
};

class result : public marks, public sports{//Derived class by hybrid inheritance//
	int tot;
	float avg;
	public :
	void show(){}
		tot=m+p+c;
		avg=tot/3.0;
		cout << "Total=" << tot << endl;
		cout << "Average=" << avg << endl;
		cout << "Average + Sports marks =" << avg+spmarks;
	}
};

void main(){
	result r;//object//
	r.getstu();
	r.getmarks();
	r.getsports();
	r.show();
	getch();
};

Example using color

#include<iostream.h>
#include<conio.h>
class colorc {
	protected:
	int a;
	public:
	void get(){
	cout<<"n Enter a value:";
	cin>>a;     
}};
 
class redc:virtual public colorc{
	protected:
	int b;
	public:
	void get1(){
	cout<<"n Enter b value";
	cin>>b;
}};
 
class greenc:virtual public colorc{
	protected:
	int c;
	public:
	void get2(){
		cout<<"n Enter c value:";
		cin>>c;    
}};
 
class yellowc:public redc,public greenc{
	public:
	void display(){
	get();    get1();    get2();
	cout<<"n Multiplication value is "<<a*b*c;    
}};
 
void main()    {
	redc a;        
	clrscr();
	a.display();    
	getch();    
}