Saturday, September 24, 2016

Multiple Inheritance

Program To Illustrate The Concept Of Multiple Inheritance:


#include<iostream>
using namespace std;
class base1
{
    int a;
    protected:
        int b;
    public:
        int c;
        void getdata()
        {
            cout<<"Enter The Values Of A,B,C\n";
            cin>>a>>b>>c;
        }
        void putdata()
        {
            cout<<"Values Are\n";
            cout<<"\nA="<<a;
            cout<<"\nB="<<b;
            cout<<"\nC="<<c;
                }
};
class base2
{
    int d;
    protected:
        int e;
    public:
        void input()
        {
            cout<<"Enter D and E\n";
            cin>>d>>e;
        }
        void output()
        {
            cout<<"\nD="<<d;
            cout<<"\nE="<<e;
        }
};
class derived:public base1,public base2
{
    int f;
    protected:
        int g;
    public:
        void getfg()
        {
            cout<<"Enter F and G\n";
            cin>>f>>g;
        }
        void putfg()
        {
            cout<<"\nF="<<f;
            cout<<"\nG="<<g;
        }
};
main()
{
    derived p;
    p.getdata();
    p.input();
    p.getfg();
    p.putdata();
    p.output();
    p.putfg();
}

Output:

Ambiguity:

In Multiple Inheritance There is an Ambiguity That If both Base Classes have same function then which function will be invoked by the object of derived class.
Because both functions are the members of derived class.
Therefore there will be an error message stating that the call is ambiguous.

Solution: 

We can solve the above problem by using scope resolution operator.

p.base1::putdata();

p.base2::putdata();

Error Message: