In C++, multiple inheritance is a feature that allows a class to inherit properties and behavior from multiple classes. This means that a class can have multiple base classes, and it can inherit properties and behavior from all of them.
Here is an example of multiple inheritance in C++:
#include <iostream>
using namespace std;
// Base class A
class A {
public:
int a;
void displayA() {
cout << "Value of a: " << a << endl;
}
};
// Base class B
class B {
public:
int b;
void displayB() {
cout << "Value of b: " << b << endl;
}
};
// Derived class C, which inherits from both class A and class B
class C : public A, public B {
public:
int c;
void displayC() {
cout << "Value of c: " << c << endl;
}
};
int main() {
C obj;
obj.a = 10;
obj.b = 20;
obj.c = 30;
obj.displayA();
obj.displayB();
obj.displayC();
return 0;
}
In this example, class C is the derived class, and it inherits from both class A and class B. This means that it has access to the a
and b
variables and the displayA()
and displayB()
functions from both base classes. It also has its own c
variable and displayC()
function.
When the displayA()
, displayB()
, and displayC()
functions are called on an object of class C, they will print the values of the a
, b
, and c
variables, respectively.