ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Multiple inheritance
    Object Oriented ProgrammingTopic 15 of 23

    Multiple inheritance

    7 minread
    1,134words
    Intermediatelevel

    Multiple Inheritance in C++

    Multiple inheritance is a feature in object-oriented programming (OOP) where a derived class can inherit from more than one base class. In C++, this allows a class to inherit characteristics (attributes and methods) from multiple classes, promoting code reuse and flexibility.

    What is Multiple Inheritance?

    In multiple inheritance, a single derived class inherits from two or more base classes. The derived class gets access to all the public and protected members of its base classes. This allows the derived class to combine the functionalities of multiple classes.

    For example, if we have two base classes Animal and Vehicle, a Car class can inherit from both to represent a "car" that is both an animal (because it might have behaviors like eat() or move()) and a vehicle (with characteristics like start() or stop()).

    Syntax of Multiple Inheritance:

    class DerivedClass : public BaseClass1, public BaseClass2 {
        // Members and methods of DerivedClass
    };
    
    • BaseClass1 and BaseClass2 are the base classes that the derived class inherits from.
    • The access specifier (public, protected, or private) determines the visibility of the base class members in the derived class.

    Example of Multiple Inheritance:

    #include <iostream>
    using namespace std;
    
    // Base class 1
    class Animal {
    public:
        void eat() {
            cout << "Animal is eating." << endl;
        }
    };
    
    // Base class 2
    class Vehicle {
    public:
        void drive() {
            cout << "Vehicle is driving." << endl;
        }
    };
    
    // Derived class that inherits from both Animal and Vehicle
    class Car : public Animal, public Vehicle {
    public:
        void honk() {
            cout << "Car is honking." << endl;
        }
    };
    
    int main() {
        Car myCar;
        myCar.eat();      // Inherited from Animal
        myCar.drive();    // Inherited from Vehicle
        myCar.honk();     // Defined in Car
    
        return 0;
    }
    

    Explanation:

    • The Car class is derived from both Animal and Vehicle classes.
    • The Car object myCar can call the methods eat() (from Animal), drive() (from Vehicle), and honk() (which is defined in the Car class itself).

    Key Points About Multiple Inheritance:

    1. Code Reusability:

      • Multiple inheritance allows you to reuse code from multiple base classes. For example, a class can inherit from both Shape (for geometric properties) and Color (for color properties).
    2. Combining Behaviors:

      • A class can inherit and combine behaviors from different base classes. For example, a class FlyingCar might inherit from both Car and Plane, combining features of both transportation methods.
    3. Complex Relationships:

      • Multiple inheritance can help model complex relationships where a class must be treated as an instance of multiple base types. This is useful when a class has more than one "role."

    Issues in Multiple Inheritance:

    While multiple inheritance provides flexibility, it can also introduce some complexities. Here are some challenges:

    1. Ambiguity Problem (Diamond Problem):

    The diamond problem occurs when two base classes have a method or member with the same name, and a derived class inherits from both base classes. The compiler may be unable to determine which version of the method or member to use.

    Example of Diamond Problem:

    #include <iostream>
    using namespace std;
    
    // Base class 1
    class A {
    public:
        void show() {
            cout << "Class A" << endl;
        }
    };
    
    // Base class 2
    class B : public A {
    public:
        void show() {
            cout << "Class B" << endl;
        }
    };
    
    // Base class 3
    class C : public A {
    public:
        void show() {
            cout << "Class C" << endl;
        }
    };
    
    // Derived class
    class D : public B, public C {
    public:
        // This will cause ambiguity because both B and C have their own show() method.
    };
    
    int main() {
        D obj;
        obj.show();  // Error: Ambiguous call to show()
        return 0;
    }
    

    Solution to Diamond Problem:

    The diamond problem can be avoided by using virtual inheritance. Virtual inheritance ensures that the base class is only included once in the derived class, resolving ambiguity.

    Example with Virtual Inheritance:

    #include <iostream>
    using namespace std;
    
    // Base class 1
    class A {
    public:
        void show() {
            cout << "Class A" << endl;
        }
    };
    
    // Base class 2, virtually inherits A
    class B : virtual public A {
    public:
        void show() {
            cout << "Class B" << endl;
        }
    };
    
    // Base class 3, virtually inherits A
    class C : virtual public A {
    public:
        void show() {
            cout << "Class C" << endl;
        }
    };
    
    // Derived class
    class D : public B, public C {
    public:
        void show() {
            cout << "Class D" << endl;
        }
    };
    
    int main() {
        D obj;
        obj.show();  // Output: Class D (no ambiguity)
        return 0;
    }
    

    Explanation:

    • In this example, both B and C virtually inherit from A, which means A will only be included once in the D class. This prevents the ambiguity when calling the show() function.

    2. Inheritance of Constructors:

    In multiple inheritance, constructors are not inherited by the derived class. Each base class's constructor must be called explicitly in the derived class.

    Example of Constructor in Multiple Inheritance:

    #include <iostream>
    using namespace std;
    
    // Base class 1
    class A {
    public:
        A() {
            cout << "Constructor of A" << endl;
        }
    };
    
    // Base class 2
    class B {
    public:
        B() {
            cout << "Constructor of B" << endl;
        }
    };
    
    // Derived class
    class D : public A, public B {
    public:
        D() {
            cout << "Constructor of D" << endl;
        }
    };
    
    int main() {
        D obj;
        // Output:
        // Constructor of A
        // Constructor of B
        // Constructor of D
        return 0;
    }
    

    Explanation:

    • The constructors of base classes A and B are called before the constructor of the derived class D.

    Summary of Multiple Inheritance in C++:

    1. Definition:

      • Multiple inheritance allows a derived class to inherit from two or more base classes.
    2. Advantages:

      • Code Reusability: The derived class can reuse code from multiple base classes.
      • Flexibility: Multiple inheritance allows you to combine different behaviors or attributes from various classes.
    3. Challenges:

      • Ambiguity Problem (Diamond Problem): When two base classes have members with the same name, ambiguity arises in the derived class. This can be resolved using virtual inheritance.
      • Constructors: Each base class's constructor must be called explicitly in the derived class, as constructors are not inherited.
    4. Virtual Inheritance:

      • To avoid ambiguity in multiple inheritance, C++ allows virtual inheritance. This ensures that base classes are only inherited once, solving the diamond problem.

    Multiple inheritance is a powerful feature, but it must be used carefully, especially in complex systems where the potential for ambiguity and confusion is higher.

    Previous topic 14
    Inheritance
    Next topic 16
    Polymorphism

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,134
      Code examples0
      DifficultyIntermediate