C++ Multiple Inheritance

ht‮//:spt‬www.theitroad.com

Multiple inheritance in C++ allows a derived class to inherit from multiple base classes. This means that a derived class can have several parent classes, each providing different sets of functionalities.

To inherit from multiple base classes, you can specify the base classes separated by a comma in the class declaration. Here's an example:

class Base1 {
public:
    void func1() {}
};

class Base2 {
public:
    void func2() {}
};

class Derived : public Base1, public Base2 {
public:
    void func3() {}
};

In this example, the Derived class inherits from both Base1 and Base2.

One important thing to keep in mind when using multiple inheritance is the possibility of the diamond problem. This can occur when two base classes of a derived class share a common base class. In this case, the common base class will have multiple instances in the derived class, which can lead to ambiguity when accessing shared properties or methods.

For example:

class Base {
public:
    void func() {}
};

class Base1 : public Base {
public:
    void func1() {}
};

class Base2 : public Base {
public:
    void func2() {}
};

class Derived : public Base1, public Base2 {
public:
    void func3() {}
};

In this example, both Base1 and Base2 inherit from Base. When Derived inherits from both Base1 and Base2, it will have two instances of Base - one through Base1 and another through Base2. This can cause ambiguity when trying to access the func() method of Base.

To resolve the diamond problem, you can use virtual inheritance. This allows the common base class to have only one instance in the derived class, ensuring that there are no ambiguities.

To use virtual inheritance, you can add the virtual keyword before the base class name in the derived class declaration:

class Base {
public:
    void func() {}
};

class Base1 : virtual public Base {
public:
    void func1() {}
};

class Base2 : virtual public Base {
public:
    void func2() {}
};

class Derived : public Base1, public Base2 {
public:
    void func3() {}
};

In this example, both Base1 and Base2 inherit from Base using virtual inheritance, ensuring that there is only one instance of Base in Derived.