Multiple Inheritance - EduardoMSU/OOP-2143 GitHub Wiki
Multiple Inheritance is a feature of object-oriented programming where a class can inherit properties and behaviors (methods) from more than one parent class. This allows a subclass to inherit characteristics from multiple classes, promoting code reuse and modularity.
Characteristic | Description |
---|---|
Inheritance from Multiple Classes | A subclass can inherit from more than one superclass, allowing it to combine functionalities from multiple sources. |
Increased Code Reusability | Methods and attributes from multiple base classes can be reused in the derived class, reducing code duplication. |
Diamond Problem | A potential problem in multiple inheritance where an ambiguity arises if two parent classes have methods or properties with the same name. |
Constructor Inheritance | The derived class may inherit constructors from multiple base classes, requiring careful management to avoid conflicts. |
Access to Multiple Parent Features | A derived class has access to the methods and properties of all its parent classes, enabling more complex behavior. |
#include <iostream>
using namespace std;
// Base class 1
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Base class 2
class Vehicle {
public:
void drive() {
cout << "This vehicle drives on roads." << endl;
}
};
// Derived class inheriting from both Animal and Vehicle
class Car : public Animal, public Vehicle {
public:
void showDetails() {
cout << "Car details: Animal and Vehicle functionalities combined!" << endl;
}
};
int main() {
Car myCar;
myCar.eat(); // From Animal class
myCar.drive(); // From Vehicle class
myCar.showDetails(); // From Car class
return 0;
}