Hybrid Inheritance in C++

There could be situations where we need to apply two or more types of inheritance to design a program. for instance, consider the case of processing the student result discussed. the weightage for sports before Finalizing the results. the weightage for sports is stored in a separate class called sports.

Hybrid Inheritance In C++
Hybrid Inheritance In C++

1.Example for hybrid inheritance

// hybrid inheritance.cpp
#include <iostream>
using namespace std;

class A
{
 	public:
 	int x;
};
class B : public A
{
 	public:
 	B()      //constructor to initialize x in base class A
 	{
 	   x = 10;
 	}
};
class C
 {
 	public:
 	int y;
 	C()   //constructor to initialize y
 	{
 	    y = 4;
        }
};
class D : public B, public C   //D is derived from class B and class C
{
 	public:
 	void sum()
 	{
 	    cout << "Sum= " << x + y;
 	}
};

int main()
{
         D obj1;          //object of derived class D
 	obj1.sum();
 	return 0;
}               	//end of program


Output:
Sum= 14
Translate »