Write a program to implement a Hybrid Inheritance In C++ With Example?

vijaya shankar.k | 3802 Views | c++ | 11 Aug 2016

 

Inheritance :

  • Inheritance is specific to object-oriented programming, where a new class is created from an existing class.
  • Inheritance (often referred to as subclasses) comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class.
  • The main advantage of inheritance is the ability to define new attributes and new methods for the subclass which are then applied to the inherited attributes and methods. 


Uses Of Inheritance :

  • It permits code reusability. 
  • Reusability saves time in program development. 
  • It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

Types Of Inheritance :

There are different types of inheritance:
  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid (Virtual) Inheritance

Hybrid Inheritance :

The method of combining any two or more forms of inheritance in single form is called hybrid inheritance.

Syntax :

class base
{
.......
};
class derived1 : public base
{
.......
};
class derived2 : public base
{
.......
};
class dervied3 : public derived1,derived2
{
.......
};

Example :

#include<iostream.h>
#include<conio.h>
int a,b,c,d,e;
class A
{
 protected:
 public:
 void getab()
 {
  cout<<"\n Enter a and b value:";
  cin>>a>>b;
 }
};
class B:public A
{
 protected:
 public:
 void getc()
 {
  cout<<"\n Enter c value:";
  cin>>c;    
 }
};
class C    
{
 protected:
 public:
 void getd()    
 {
  cout<<"\n Enter d value:";
  cin>>d;    
 }
};
class D:public B,public C    
{
 protected:
 public:
 void result()    
 {
  getab();    
  getc();
  getd();    
  e=a+b+c+d;
  cout<<"\n Addition is :"<<e; 
 }
};
 void main()    
{
 clrscr();
 D d1;
 d1.result();
 getch();        
}

Sample Output :

Enter a and b value : 2 7
Enter c value : 10
Enter d value : 5
Addition is : 24