Understanding the Essentials of Multiple Inheritance in C++

Inheritance is one of the most important concepts of Object-Oriented Programming (OOP). It is the ability of a class to inherit or derive the properties from another class. Inheritance enhances the code readability and allows the user to reuse the code instead of writing it repeatedly. To understand the concept of inheritance, you must learn about two terms on which they based the whole concept of inheritance, and are going to be mentioned a lot whenever there is a discussion about inheritance. These two terms are:

  • Derived Class or Child Class: The class that derives the properties and characteristics of another class is known as the derived class.
  • Base Class or Parent Class: The class whose properties are inherited by the derived class is known as the base class.

There are mainly five types of inheritance in C++, they are mentioned below:

  • Single Inheritance in C++
  • Multiple Inheritance in C++
  • Multilevel Inheritance in C++
  • Hierarchical Inheritance in C++
  • Hybrid Inheritance in C++

Multiple Inheritance in C++

Multiple Inheritance in C++ is one of the five types of inheritances provided in C++ where you can derive a class from multiple classes. This means that a derived class can have over one base class. To clearly understand Multiple Inheritance in C++, consider the code snippet given below:

class father

{

    // contains the traits of the father

};

class mother

{

    //contains the traits of the mother

};

 class child: public father, public mother

{

public:

    //class definition

}; 

The above code represents the relationship of a child with his mother and father. A child inherits the characteristics of both his mother and father, such as height, color complexion, and other genetic traits. Similarly, the father and the mother class both contain some information that the child class inherits. Therefore, the child class is a derived class of the father and the mother class.

Syntax of Implementing Multiple Inheritance in C++

The following syntax can achieve Multiple Inheritance in C++:

class base_class_1

{

    // class definition

} 

class base_class_2

{

    // class definition

} 

class derived_class: access_modifier base_class_1, access_modifier base_class_2

{

    // class definition

}

Description of the syntax:

  • access_modifier: It provides the access modifier in the class declaration as it specifies how the derived class is inheriting the base class.
  • base_class: There can be over one base class, from which the derived class inherits its properties.
  • derived_class: This is the derived class that can inherit multiple base classes using the same or different access specifier.

Visibility Modes in Multiple Inheritance in C++

The visibility mode specifies the control over the inherited members within the derived classes. A class can inherit a base class in three visibility modes:

  • Public Visibility Mode:

In the public visibility mode, the public and protected members of the base class are inherited by the derived class retaining their access specifiers. This means that public members remain public and the protected members also remain protected. The derived class can directly access these members. However, the private members of the base class are not directly accessible to the derived class.

class base_class_1

{

    // class members

} 

class base_class_2

{

    // class members

} 

class derived_class: public base_class_1, public base_class_2

{

    // base_class_1 and base_class_2 members

    // public becomes public

    // protected becomes protected

}

  • Protected Visibility Mode:

In the protected visibility mode, the derived class inherits the public and protected members of the base class in the protected mode. This means that public and protected members of the parent class become protected. And it does not inherit the private members and hence is not accessible directly. 

  • Private Visibility Mode:

In the private visibility mode, it inherits the base class members privately. This means that the public and protected members of the base class become private for the derived class. These members can now be accessed only by the member functions of the derived class. And since the private members can not be inherited, it can also not inherit these members further.

class base_class_1

{

    // class members

} 

class base_class_2

{

    // class members

} 

class derived_class: protected base_class_1, private base_class_2

{

    // base_class_1

    // public becomes protected

    // protected becomes protected 

    // base_class_2

    // members cannot be inherited

}

The following chart summarizes the control of the derived classes over the members of the base class in different visibility modes :

DERIVED CLASS

DERIVED CLASS

DERIVED CLASS

BASE CLASS

PUBLIC

PROTECTED

PRIVATE

PUBLIC

Public

Protected

Private

PROTECTED

Protected

Protected

Private

PRIVATE

Not Inherited / Remains Private

Not Inherited / Remains Private

Not Inherited / Remains Private

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Advantages of Multiple Inheritance in C++

  1. Multiple Inheritance in C++ allows a derived class to inherit more properties and characteristics since it has multiple base classes.
  2. It proves to be beneficial to design various design patterns. Some of these patterns are:
  1. Adapter pattern: This pattern is used when you need to adapt to another interface with your class. For this, Multiple Inheritance in C++ plays a big role in swapping an interface with another.
  2. Observer patterns: This pattern is used to maintain a list of observers by creating a class.

The Dreaded Diamond problem

The dreaded diamond problem occurs when there is a class structure similar to the following: 

MultipleInheritanceInCpp_Flowchart_1

The 2 superclasses of the Derived_class_3 that are Derived_class_1 and Derived_class_2 have a common base class i.e. Base_class. So, there will be 2 copies of all attributes of the Base_class. When you create an object of the derived class Derived_class_3, it contains two copies of the Base_class. This situation can cause ambiguities. Consider the following example to understand this dreaded diamond situation:

#include <iostream>

using namespace std;

// base class

class Base_class

{

public:

    int x;    

    // constructor of the base class

    Base_class()

    {

        cout << "I am the constructor of Base_class.\n\n";

    }

}; 

// derived class 1

class Derived_class_1 : public Base_class

{

public:

    // constructor of the Derived_class_1

    Derived_class_1() 

    {

        cout << "I am the constructor of Derived_class_1.\n\n";

    }

}; 

// derived class 2

class Derived_class_2 : public Base_class

{

public:

    // constructor of the Derived_class_2

    Derived_class_2() 

    {

        cout << "I am the constructor of Derived_class_2.\n\n";

    }

}; 

// derived class 3

class Derived_class_3 : public Derived_class_1, public Derived_class_2

{

public:

    // constructor of the Derived_class_3

    Derived_class_3() 

    {

        cout << "I am the constructor of Derived_class_3.\n\n";

    }

};

int main()

{

    Derived_class_3 obj;

}

MultipleInheritanceInCpp_1. 

In the above example, when you create an object of the derived class Derived_class_3, the constructor of the Base_class is called two times. This clearly shows that there are two copies of the Base_class. 

    // obj is the object of the Derived_class

    // x is a data member of the Base_class

    obj.x = 100;

Ambiguity will be caused in the above expression as there are 2 copies of the data member ‚Äúx‚ÄĚ. So it is not clear which x needs to be updated here. This ambiguous situation can be removed in two ways:

  1. Using the scope resolution operator (::).
  2. Using the virtual keyword.

How to Solve the Ambiguity in the Diamond Problem?

  • Using the Scope Resolution Operator.

The scope resolution operator can be used before the data member to be accessed. This allows you to manually select that copy that needs to be updated. The following expression explains this:

      // obj is the object of the Derived_class

      // x is a data member of the Base_class

      obj.x = 100;    <- STATEMENT 1

      obj.Derived_class_1::x = 100;   <- STATEMENT 2

In the above expression, STATEMENT 1 was causing ambiguity in the previous example. So, replacing it with STATEMENT 2 using the scope resolution operator clarifies that the copy of Derived_class_1 is to be accessed and thus it will remove the ambiguity.

The following example illustrates how to avoid ambiguous situations using the scope resolution operator.

#include <iostream>

using namespace std; 

// base class

class Base_class

{

public:

    int x = 10;

};

// derived class 1

class Derived_class_1 : public Base_class

{

public:

    int d1 = 20;

};

// derived class 2

class Derived_class_2 : public Base_class

{

public:

    int d2 = 30;

};

// derived class 3

class Derived_class_3 : public Derived_class_1, public Derived_class_2

{

public:

    int d3;

};

int main()

{

    Derived_class_3 obj;

    cout << "The previous value of x is: " << obj.Derived_class_1::x << "\n\n";

    // obj is the object of the Derived_class

    // x is a data member of the Base_class

    // obj.x = 100                  /** ambiguous **/

    obj.Derived_class_1::x = 100;   /** now unambiguous  **/

    obj.d3 = obj.Derived_class_1::x + obj.d1 + obj.d2;

    cout << "The sum is: " << obj.d3 << "\n\n";

    return 0;

}

MultipleInheritanceInCpp_2 

In the above example, the scope operator (::) was used to manually specify that the Derived_class_1‚Äôs version of ‚Äúx‚ÄĚ needs to be accessed.¬†

Although the scope resolution method avoids the ambiguous situation, it does not prevent the creation of 2 copies of the Base_class. The next method i.e. using the virtual classes solves this problem. 

  • Using the Virtual Keyword.

The virtual keyword can prevent the creation of multiple copies of the base class in a diamond structure. Declaring the Base_class as virtual when the derived classes inherit it, will create only one copy of the Base_class instead of making multiple copies. The virtual keyword should be used in the following way:

class Derived_class_1 : virtual public Base_class

class Derived_class_2 : virtual public Base_class

After declaring the derived class in the above manner, you can access the data member x of the base class in the usual way without any ambiguities.

obj.x = 100                    /** now unambiguous **/

The above expression which gave ambiguous errors previously is now resolved and can be used without giving any errors because now there is only one copy of the base class.

The following example illustrates the working of the virtual base classes in Multiple Inheritance in C++.

#include <iostream>

using namespace std;

// base class

class Base_class

{

public:

    int x = 10;

};

// derived class 1

class Derived_class_1 : virtual public Base_class

{

public:

    int d1 = 20;

};

// derived class 2

class Derived_class_2 : virtual public Base_class

{

public:

    int d2 = 30;

};

// derived class 3

class Derived_class_3 : public Derived_class_1, public Derived_class_2

{

public:

    int d3;

};

int main()

{

    Derived_class_3 obj;

    cout << "The previous value of x is: " << obj.x << "\n\n";

    // obj is the object of the Derived_class

    // x is a data member of the Base_class

    obj.x = 100;                    /** now unambiguous **/

    obj.d3 = obj.x + obj.d1 + obj.d2;

    cout << "The sum is: " << obj.d3 << "\n\n";

    return 0;

}

MultipleInheritanceInCpp_3

In the above example, the derived classes inherit the base class as virtual. This only makes one copy of the base class instead of creating multiple copies. Now all data members and member functions of the Base_class can be accessed in the usual way without any ambiguities. 

Examples of Multiple Inheritance in C++

The following examples illustrate various implementations of Multiple Inheritance in C++:

Example 1

#include <iostream>

using namespace std;

// base class 1

class Mathematics

{

public:

    int mathMarks = 99;

};

// base class 2

class English

{

public:

    int engMarks = 90;

}; 

// derived class

class Result: public Mathematics, public English

{

public:

    void total()

    {

        int result;     

        // accessing the data members

        // of the base classes

        result = ((mathMarks + engMarks) * 100) / 200;

        cout << " The overall result is: " << result << "%";

        cout << "\n\n";

    }

};

int main()

{

    // create object of the derived class

    Result obj;

    obj.total();   // call total() function of the derived class

    return 0;

}

MultipleInheritanceInCpp_4.

In the above example, the class Result is inheriting the properties of the base classes Mathematics and English. The data members of these classes are accessible to the derived class Result. So, the total() function of the derived class calculates the percentage using the member variables of the base classes.

Example 2

#include <iostream>

using namespace std;

// base class 1

class Mathematics

{

public:

    void mathMarks()

    {

        cout << "Marks in mathematics is 99\n\n";

    }

}; 

// base class 2

class English

{

public: 

    void engMarks()

    {

        cout << "Marks in English is 90\n\n";

    }

}; 

// derived class

class Result: public Mathematics, public English

{

public:

    void displayMarks()

    {

        // accessing the member functions 

        // of the base classes

        mathMarks();

        engMarks();

    }

}; 

int main()

{

    // create an object of the derived class

    Result obj;

    obj.displayMarks();   // call displayMarks() function of the derived class 

    return 0;

}

MultipleInheritanceInCpp_5.

In the above example, the derived class Result inherits the properties of the base classes Mathematics and English. The displayMarks() function of the derived class accesses the member functions of the base classes. When the displayMarks() method of the derived class is called, it displays the marks in Mathematics and English.

Example 3

#include <iostream>

using namespace std;

// base class 1

class Mathematics

{

public:

    void display_math(int mathMarks)

    {

        cout << "Marks in Mathematics: " << mathMarks;

        cout << "\n\n";

    }

};

// base class 2

class English

{

public:

    void display_eng(int engMarks)

    {

        cout << "Marks in English: " << engMarks;

        cout << "\n\n";

    }

}; 

// derived class inheriting base class 1 and base class 2

class Physics: public Mathematics, public English

{

public:

    void display_phy(int phyMarks)

    {

        cout << "Marks in Physics: " << phyMarks;

        cout << "\n\n";

    }

};

int main()

{

    // create object of the derived class

    Physics obj;

    // call functions of the base classes

    // and the derived class.

    obj.display_math(99);

    obj.display_eng(90);

    obj.display_phy(95);

    return 0; 

}

MultipleInheritanceInCpp_6

In the above example, the class Physics inherits the base classes Mathematics and English in public mode. So the object of the derived class accesses the member functions of the base classes. The object obj of the class Physics can call the parameterized functions display_math() and display_eng() of the base classes.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Difference Between Multiple Inheritance in C++ and Multilevel Inheritance in C++

Multiple Inheritance in C++

The inheritance in which a class can be derived from more than one class or a class can have more than one base class is known as multiple inheritances in C++. The following diagram shows the basic structure of Multiple Inheritance in C++.

MultipleInheritanceInCpp_Flowchart_2

#include <iostream>

using namespace std;

// base class 1

class Gadgets

{

    public:

        // constructor of the base class 1

        Gadgets()

        {

            cout << "I am a gadget.\n\n";

        }

}; 

// base class 2

class Smartphone

{

    public:

        // constructor of the base class 2

        Smartphone()

        {

            cout << "I am a smartphone.\n\n";

        }

}; 

// derived class inheriting base class 1 and base class 2

class Android: public Gadgets, public Smartphone

{

    public:

        // constructor of the derived class

        Android()

        {

            cout << "I am an android device.\n\n";;

        }

}; 

int main()

{

    // create object of the derived class

     Android obj;    // constructor of base class 1, 

                    // base class 2, derived class will be called

     return 0;

}

MultipleInheritanceInCpp_7

In the above example, there are two base classes Gadget and Smartphone. The derived class Android inherits the properties of both of these classes. When an instance of this derived class is created, the constructor of the base classes and the derived class is called.

Multilevel Inheritance

The inheritance in which a derived class acts as a base class for another derived class i.e., multiple levels of inheritance is called multilevel inheritance. The following diagram shows the basic structure of Multilevel Inheritance in C++.

MultipleInheritanceInCpp_Flowchart_3.

#include <iostream>

using namespace std;

// base class

class Gadgets

{

public:

    Gadgets()

    {

        cout << "I am a gadget.\n\n";

    }

};

// derived class 1

class Android: public Gadgets

{

public:

    Android()

    {

        cout << "I am an android device.\n\n";

    }

};

// derived class 2

class Smartphone: public Android

{

public:

    Smartphone()

    {

        cout << "I am a smartphone working on android.\n\n";

    }

};

int main()

{

    // create an object of the derived class Smartphone

    Smartphone obj; 

    return 0;

}

MultipleInheritanceInCpp_8 

In the above example, there are three classes Gadget, Android, and Smartphone. The class Android inherits its properties from the base class Gadget. And the class Smartphone inherits the properties of the class Android. So when an instance of the Smartphone class creates the constructor of the class Gadget, Android, and Smartphone are called respectively.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Final Thoughts!

In this article, you learned about the fundamentals of inheritance in C++ and multiple inheritance in C++. You looked at the syntax that will help you to implement multiple inheritance in C++, the various visibility modes, advantages, and the ambiguous diamond problem in C++. You also looked at how to solve this ambiguity and several other helpful examples of multiple inheritance in C++. Finally, you saw the difference between multiple and multilevel inheritance in C++.

If you are looking for a career in full-stack web development, you should definitely check out our complete Full Stack Web Development certification training program with a duration of over 9 months. This is a comprehensive training that will walk you through some of the most trending technologies and skills such as OOPS, Java, Agile, Hibernate, JPA, Spring, DevOps, HTML, CSS, AWS, Servlets, and a complete capstone project at the end.

To know more about other important concepts in C++, you can check out our complete tutorial on C++ for beginners.

If you are keen to learn new topics and technologies, you can check out our complete list of free online courses. 

If you have any queries in this ‚Äúmultiple inheritance in C++‚ÄĚ article or suggestions for us, please mention them in the comment box and our experts answer them for you as soon as possible.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.