Cover Image for Multiple Inheritance in C++
105 views

Multiple Inheritance in C++

Multiple inheritance in C++ is a feature that allows a class to inherit properties and behaviors from more than one base class. In other words, a derived class can have multiple parent classes. This is a powerful concept that enables you to create complex class hierarchies and reuse code from multiple sources.

Here’s how multiple inheritance works in C++:

  1. Define Base Classes: Start by defining multiple base classes, each with its own set of member functions and data members.
C++
 class A {
 public:
     void functionA() {
         std::cout << "Function from class A" << std::endl;
     }
 };

 class B {
 public:
     void functionB() {
         std::cout << "Function from class B" << std::endl;
     }
 };
  1. Create a Derived Class: Then, create a derived class that inherits from multiple base classes. You can list the base classes in a comma-separated list after a colon in the derived class definition.
C++
 class C : public A, public B {
 public:
     void functionC() {
         std::cout << "Function from class C" << std::endl;
     }
 };
  1. Using the Derived Class: You can create objects of the derived class and access the member functions and data members inherited from both base classes.
C++
 int main() {
     C obj;
     obj.functionA(); // Calls function from class A
     obj.functionB(); // Calls function from class B
     obj.functionC(); // Calls function from class C

     return 0;
 }

In this example, the class C inherits both from class A and class B, so it has access to all the member functions and data members of both base classes.

Multiple inheritance can be a powerful tool for code reuse and creating complex class hierarchies, but it also introduces challenges, such as the potential for ambiguity if two base classes have members with the same name. In such cases, you can use scope resolution (Base::function()) or virtual inheritance to resolve ambiguities.

Here’s an example that demonstrates how to handle ambiguity when two base classes have members with the same name:

C++
class A {
public:
    void function() {
        std::cout << "Function from class A" << std::endl;
    }
};

class B {
public:
    void function() {
        std::cout << "Function from class B" << std::endl;
    }
};

class C : public A, public B {
public:
    void callFunctionA() {
        A::function(); // Call function from class A
    }

    void callFunctionB() {
        B::function(); // Call function from class B
    }
};

In this modified example, class C provides member functions callFunctionA and callFunctionB to call the specific functions from classes A and B to resolve the ambiguity.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS