Multiple inheritance is a feature in C++ that allows a class to inherit from multiple base classes. In other words, it enables a class to have more than one parent class. This is in contrast to single inheritance, where a class can only inherit from a single parent class.
Advantages:
Provides a more natural way of modeling objects in certain situations. For example, a class that represents a student may inherit from both a ’Person’ class and a ’StudentProgram’ class to represent the person’s personal information as well as their academic program. Allows for code reuse by inheriting from multiple classes that provide useful functionality, rather than having to duplicate the code in each class. Can result in more efficient code, as certain optimizations can be made possible by using multiple inheritance.
Disadvantages:
Can lead to ambiguity problems when two or more base classes define a method with the same name. In such cases, it’s necessary to use scope resolution to specify which method should be called. Can make the code more complex and harder to understand, especially when the hierarchy of classes becomes more complicated. Can result in the ’diamond problem’, where a derived class inherits from two or more classes that themselves inherit from a common base class. This can lead to ambiguity and code duplication if not properly handled.
Example:
class Person {
public:
Person(string name) : name_(name) {}
virtual void speak() {
cout << "My name is " << name_ << endl;
}
protected:
string name_;
};
class StudentProgram {
public:
StudentProgram(string program) : program_(program) {}
virtual void printProgram() {
cout << "My program is " << program_ << endl;
}
protected:
string program_;
};
class Student : public Person, public StudentProgram {
public:
Student(string name, string program)
: Person(name), StudentProgram(program) {}
void introduce() {
speak();
printProgram();
}
};
int main() {
Student s("Alice", "Computer Science");
s.introduce();
return 0;
}
In the example above, we have a Person class and a StudentProgram class that provide some basic functionality for representing a person and their academic program, respectively. The Student class inherits from both Person and StudentProgram to represent a student with a name and academic program. The introduce method in the Student class demonstrates the use of both base classes to provide some useful functionality.