Object Oriented Programming - Old Questions

4. Explain the syntax and rules of multiple inheritance in C++ with example.

5 marks | Asked in 2072

When a class is derived from two or more base classes, such inheritance is called Multiple Inheritance. Multiple Inheritance in C++ allow us to combine the features of several existing classes into a single class.


Syntax:

class base_class1
{
    // body of the class
};
class base_class2
{
    //body of the class
};
class derived_classname : visibility_mode base_class1, visibility_mode base_class2
{
    //body of the class
};

Example:

#include <iostream>  

using namespace std;  

class A  

{  

    protected:

      int a;  

    public:  

    void get_a(int n)  

    {  

        a = n;  

    }  

};  

class B  

{  

    protected:

      int b;  

    public:  

    void get_b(int n)  

    {  

        b = n;  

    }  

};  

class C : public A, public B  

{  

   public:  

    void display()  

    {  

        cout << "The value of a is : " <<a<<endl;  

        cout << "The value of b is : " <<b<<endl;  

        cout <<"Addition of a and b is : "<<a+b;  

    }  

};  

int main()  

{  

   C obj;  

   obj.get_a(10);  

   obj.get_b(20);  

   obj.display();  

   return 0;  

}