Simple Program For Hybrid Inheritance in C++


It is a combination of two types of inheritance namely the multiple and hierarchical Inheritance. The following is a schematic representation.

Simple Example of Hybrid Inheritance in C++

#include<iostream> using namespace std; class base1{ public: void msg1(){ cout<<"base1 - msg1"<<endl; } }; class base2{ public: void msg2(){ cout<<"base2 - msg2"<<endl; } }; class der1 : public base1{ public: void msg3(){ cout<<"der1 - msg3"<<endl; } }; class der2 : public der1, public base2{ public: void msg4(){ cout<<"der2 - msg4"<<endl; } }; int main(){ base1 b1; b1.msg1(); base2 b2; b2.msg2(); der1 d1; d1.msg1(); d1.msg3(); der2 d2; d2.msg1(); d2.msg2(); d2.msg3(); d2.msg4(); return 0; }

Output:-

base1 - msg1
base2 - msg2
base1 - msg1
der1 - msg3
base1 - msg1
base2 - msg2
der1 - msg3
der2 - msg4

Explanation of the program

In this program, base1 and base2 are the base classes. The class der1 is derived from base1 and class der2 is derived from base and der1.