Multiple inheritance is a feature of C++ that allows a derived class to inherit from multiple base classes. To implement multiple inheritance, you can use a comma-separated list of base classes in the class declaration. Here's an example of how to implement multiple inheritance in C++:
c++#include <iostream>
using namespace std;
// Define a base class A
class A {
public:
void printA() {
cout << "This is class A" << endl;
}
};
// Define another base class B
class B {
public:
void printB() {
cout << "This is class B" << endl;
}
};
// Define a derived class C that inherits from A and B
class C: public A, public B {
public:
void printC() {
cout << "This is class C" << endl;
}
};
int main() {
C c;
// Call member functions of class A, B, and C
c.printA();
c.printB();
c.printC();
return 0;
}
In this example, we define two base classes A
and B
, each with a public member function that prints a message to the console. We then define a derived class C
that inherits from both A
and B
using the public
access specifier.
In the main()
function, we create an object c
of the C
class and call its member functions printA()
, printB()
, and printC()
to demonstrate that it has inherited the member functions of both A
and B
.
Note that when you inherit from multiple base classes, it's possible for those base classes to have member functions with the same name. In that case, you can use the scope resolution operator ::
to specify which version of the member function you want to call. For example, if both A
and B
had a member function called print()
, you could call the version from A
using c.A::print()
, or the version from B
using c.B::print()
.
Comments
Post a Comment