Class 1 Class 2 Class 3 Class 4 Class 5 Class 6 Class 7 Class 8

Multiple Inheritance in C++

Share Now

Multiple Inheritance in C++, In object-oriented programming, inheritance allows a class to reuse properties and behaviors of another class. While single inheritance connects one base class to one derived class, multiple inheritance extends this idea by allowing a derived class to inherit from two or more base classes simultaneously.

Multiple Inheritance in C++

In C++, multiple inheritance is a feature where a class can inherit from more than one base class (parent class). This helps the child class to get features like functions and variables from both parents. For example, if a child wants to learn cooking from Mom’s class and from Dad’s class.

Syntax:

class Base1 {
    // members of Base1
};

class Base2 {
    // members of Base2
};

class Derived : public Base1, public Base2 {
    // members of Derived
};

Problems in Multiple Inheritance

  • Ambiguity Problem: In this both parents have a function with the same name, which makes it difficult for the compiler to understand which one of the classes it has to use.
  • Diamond Problem: In this, the structure looks like a diamond. In this, the child class inherits the function and variable from two parent classes, and both parent classes inherit from the first class. Because of this, the child class gets two copies of the parent class, which reduces the confusion.

Example of Multiple Inheritance

Suppose there are two classes, “Teacher” and “Writer”, and one drive class, which is “Person”. In this example, both the parent classes “Teacher” and “Writer” will be inherited by the derived class “Person”.

#include <iostream>
using namespace std;

// Base class 1
class Teacher {
public:
    void teach() {
        cout << "Teaching students" << endl;
    }
};

// Base class 2
class Writer {
public:
    void write() {
        cout << "Writing articles" << endl;
    }
};

// Derived class inherits from both Teacher and Writer
class Person : public Teacher, public Writer {
public:
    void introduce() {
        cout << "I am a person with multiple skills" << endl;
    }
};

int main() {
    Person p;
    p.introduce(); // From Person
    p.teach();     // From Teacher
    p.write();     // From Writer
    return 0;
}

Disclaimer: We have provide you with the accurate handout of “Multiple Inheritance in C++“. If you feel that there is any error or mistake, please contact me at anuraganand2017@gmail.com. The above study material present on our websites is for education purpose, not our copyrights.

Images and content shown above are the property of individual organisations and are used here for reference purposes only. To make it easy to understand, some of the content and images are generated by AI and cross-checked by the teachers.

cbseskilleducation.com

Leave a Comment