C++ Programs Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance in C++. It is done by combining multiple inheritance and multilevel inheritance to achieve flexibility and code reusability.
Syntax
/* Multilevel inheritance */
class A {
// code
};
class B : public A {
// code
};
class C : public B {
// code
};
/* Multiple inheritance */
class D {
// code
};
class E {
// code
};
class F : public D, public E {
// code
};
/* Hybrid inheritance */
class G : public C, public F {
// code
};
Example
#include<iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class LandAnimal : public Animal {
public:
void walk() {
cout << "Walking on land..." << endl;
}
};
class WaterAnimal : public Animal {
public:
void swim() {
cout << "Swimming in water..." << endl;
}
};
class Amphibian : public LandAnimal, public WaterAnimal {
public:
void jump() {
cout << "Jumping..." << endl;
}
};
int main() {
Amphibian frog;
frog.walk();
frog.swim();
frog.jump();
frog.eat();
return 0;
}
Output
Walking on land...
Swimming in water...
Jumping...
Eating...
Explanation
In the above example, we have created three classes, "Animal", "LandAnimal", and "WaterAnimal", with each one inheriting from the previous one using multilevel inheritance. We have also created a class "Amphibian" that inherits from "LandAnimal" and "WaterAnimal" using multiple inheritance.
The "Amphibian" class can perform all the functions of its parent classes, i.e., it can walk on land, swim in water, and eat. Additionally, it has a jump function that is unique to the "Amphibian" class.
Use
Hybrid inheritance is used when none of the individual inheritance patterns can meet the requirements of a problem domain. It is used to achieve maximum flexibility and code reusability.
Important Points
- Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
- Multiple inheritance allows a class to inherit from multiple base classes.
- Multilevel inheritance allows a class to inherit from a base class that has already inherited from another base class.
- Hybrid inheritance is used to achieve maximum flexibility and code reusability.
- It can be complex and can lead to ambiguity, so it should be used with caution.
Summary
In summary, hybrid inheritance in C++ is a powerful inheritance pattern that combines multiple inheritance and multilevel inheritance to achieve maximum flexibility and code reusability. It is used when none of the individual inheritance patterns can meet the requirements of a problem domain. However, it can be complex and may lead to ambiguity, so it should be used with caution.