Hybrid inheritance is a combination of multiple inheritance types, such as single, multiple, multilevel, or hierarchical inheritance. It is used to demonstrate various inheritance models in a single program.
📌 Multiplication using Hybrid Inheritance in C++
Let's create a C++ program to perform multiplication using hybrid inheritance.
🚀 Approach
- Base Class (
Base
) → Contains a common input function. - Derived Class 1 (
Multiply
) → Multiplies two numbers. - Derived Class 2 (
Factor
) → Adds a factor to multiplication. - Final Derived Class (
Result
) → Displays the final result.
🔹 C++ Code for Multiplication using Hybrid Inheritance
#include <iostream>
using namespace std;
// Base Class
class Base {
protected:
int num1, num2;
public:
void getInput() {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
}
};
// First Derived Class
class Multiply : public Base {
protected:
int product;
public:
void calculateProduct() {
product = num1 * num2;
}
};
// Second Derived Class
class Factor {
protected:
int factor;
public:
void setFactor() {
cout << "Enter multiplication factor: ";
cin >> factor;
}
};
// Final Derived Class (Hybrid Inheritance)
class Result : public Multiply, public Factor {
public:
void displayResult() {
calculateProduct(); // Calling Multiply's function
cout << "Multiplication Result: " << product << endl;
cout << "Final Result after applying factor: " << product * factor << endl;
}
};
int main() {
Result obj;
obj.getInput();
obj.setFactor();
obj.displayResult();
return 0;
}
🔹 Example Output
Enter two numbers: 5 4
Enter multiplication factor: 3
Multiplication Result: 20
Final Result after applying factor: 60
📌 Explanation
- Class
Base
→ Takes two numbers as input. - Class
Multiply
(Derived fromBase
) → Computes their multiplication. - Class
Factor
→ Takes a factor input. - Class
Result
(Derived fromMultiply
&Factor
) → Computes the final result.
🔹 Hybrid inheritance is useful when combining different inheritance models.
🚀 Let me know if you need more variations! 🚀
0 Comments