Multiple Inheritance in C++: Definition and Example
multiple inheritance is a feature where a class can inherit from more than one base class. This allows the derived class to combine behaviors and properties from multiple sources into one.How It Works
Multiple inheritance in C++ means a class can have more than one parent class. Imagine you have two different toolboxes, each with unique tools. By inheriting from both, your new toolbox has all the tools from both parents combined.
This allows the new class to use functions and variables from both base classes. However, if both parents have a function with the same name, the derived class must clarify which one to use to avoid confusion.
Example
This example shows a class SmartPhone inheriting from both Camera and Phone classes, combining their features.
#include <iostream> using namespace std; class Camera { public: void takePhoto() { cout << "Photo taken" << endl; } }; class Phone { public: void makeCall() { cout << "Calling..." << endl; } }; class SmartPhone : public Camera, public Phone { // Inherits both takePhoto() and makeCall() }; int main() { SmartPhone sp; sp.takePhoto(); // From Camera sp.makeCall(); // From Phone return 0; }
When to Use
Use multiple inheritance when a new class needs to combine features from different classes that represent distinct concepts. For example, a SmartPhone can inherit camera features and phone features separately.
This helps keep code organized and reusable. But be careful: if two base classes have similar functions or data, it can cause conflicts that need to be resolved explicitly.
Key Points
- Multiple inheritance allows a class to inherit from more than one base class.
- It combines features from all parent classes into one derived class.
- Conflicts can occur if base classes have members with the same name.
- Explicit resolution is needed to avoid ambiguity.
- Useful for modeling objects that naturally combine multiple roles or capabilities.