What is Multiple Inheritance in C++

multiple-inheritance

Multiple Inheritance

  • As we know, inheritance is the process of extending the capabilities of one class to  another class
  • It is interesting to know, a child class in multiple inheritances a have more than one parent class  at a time
  • Definition: The process where a single class acquiring the behaviors and capabilities from  multiple classes called multiple inheritance

Syntax to Implement Multiple Inheritance

class parent1
{
......;
};
class parent2
{
......;
};
class child:accces1 parent1,access2 parent2//multiple parents
{
-----;//data of both parent1 +parent2+child
};
  • The class that is acquiring the behaviors is called child class or derived class or subclass
  • The class from which behaviors are taken is called parent class or superclass or base class
  • Here parent1 and parent2 are superclasses for a single derived class child

Example Program to understand Multiple Inheritance

#include
using namespace std;
class P1//parent 1
{
public:
void m1()
{
cout<<"\n"<<"m1 from parent p1-3sh";
}
};
class P2//parent 2
{
public:
void m2()
{
cout<<"\n"<<"m2 from parent p2-rish";
}
};
class child:public P1,public P2//multiple parents p1,p2
{
public:
void m3()
{
cout<<"\n"<<"m3 from childs own code-3shrish";
}
};
main()
{
child c;
c.m1();//derived from parent p1
c.m2();//derived from parent p2
c.m3();//Its own Method
}
Output
m1 from parent p1-3sh
m2 from parent p2-rish
m3 from child's own code -3shrish
Here child class is having multiple parent P1 and P2 .it took m1() from p1 and m2() from P2 and its own  method m3() hence child is having totally 3 methods

Ambiguity problem in multiple inheritance

Some times two class can have the same method name and If a child class inherits multiple classes in such case, there is an ambiguity problem in naming
#include
using namespace std;
class P1
{
public:
void m1()
{
cout<<"\n"<<"m1 from parent p1-3sh";
}
};
class P2
{
public:
void m1()//same method name as P1
{
cout<<"\n"<<"m2 from parent p2-rish";
}
};
class child:public P1,public P2//multiple parents p1,p2
{
// which method shoud inherit m1 ()from P1 or P2?
public:
void m3()
{
cout<<"\n"<<"m3 from childs own code-3shrish";
}
};
main()
{

child c;
//c.m1();//derived from parent p1
// [Error] request for member 'm1' is ambiguous
c.m3();//Its own Method and valid 
}
Output
m3 from childs own code-3shrish
  • In the above example, there is m1() in both classes P1 and P2 and child inherits both classes P1 and P2  In such it should inherit which m1() i.e m1() from class P1 or P2. Hence ambiguity is created upon calling m1();
  • Hence, for this reason, OO-designers decided not to have Multiple inheritance in Java Language