SlideShare a Scribd company logo
1 of 21
Multiple Inheritance
Multiple Inheritance
• If a class is derived from two or more base classes then it is called
multiple inheritance. In C++ multiple inheritance a derived class
has more than one base class.
• Multiple inheritance enables a derived class to inherit members
from more than one parent.
Difference in Multipe Inheritance & Multilevel
Inheritance
• Though but multiple and multilevel sounds like same but they
differ hugely in meaning. In multilevel inheritance, we have
multiple parent classes whereas in in multiple inheritance we have
multiple base classes.
• To put it in simple words, in multilevel inheritance, a class is
derived from a class which is also derived from another base class.
And these levels of inheritance can be extended. On the contrary,
in multiple inheritance, a class is derived from two different base
classes.
For example
• Multilevel inheritance : Inheritance of characters by a
child from father and father inheriting characters from
his father (grandfather)
• Multiple inheritance : Inheritance of characters by a
child from mother and father
C++ Multiple Inheritance Block Diagram
C++ Multiple Inheritance Syntax
• class A
• {
• ..........
• };
• class B
• {
• ...........
• } ;
• class C : acess_specifier A,access_specifier A // derived class from A and B
• {
• ...........
• } ;
C++ Multiple Inheritance Example
#include
using namespace std;
class A
{public:
int x;
void getx()
{
cout << "enter value of x: "; cin >>
x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "enter value of y: "; cin
>> y;
}
};
C++ Multiple Inheritance Example
class C : public A, public B //C is
derived from class A and class B
{
public:
void sum()
{cout << "Sum = " << x + y;
}
};
int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program
C++ Multiple Inheritance Example
Output
enter value of x: 5
enter value of y: 4
Sum = 9
C++ Multiple Inheritance Example 2
Let’s say we wanted to write a program to keep track of a
bunch of teachers. A teacher is a person. However, a
teacher is also an employee (they are their own employer
if working for themselves). Multiple inheritance can be
used to create a Teacher class that inherits properties
from both Person and Employee. To use multiple
inheritance, simply specify each base class (just like in
single inheritance), separated by a comma.
C++ Multiple Inheritance Example 2
C++ Multiple Inheritance Example 2
• std::string getName() { return m_name; }
• int getAge() { return m_age; }
• };
• class Employee
• {
• private:
• std::string m_employer;
• double m_wage;
• public:
• Employee(std::string employer, double wage)
• : m_employer(employer), m_wage(wage)
• {
• }
#include <string>
class Person
{
private:
std::string m_name;
int m_age;
public:
Person(std::string name, int age)
: m_name(name), m_age(age)
{
}
C++ Multiple Inheritance Example 2
public:
Teacher(std::string name, int age,
std::string employer, double wage, int
teachesGrade)
: Person(name, age), Employee(employer,
wage), m_teachesGrade(teachesGrade)
{
}
};
std::string getEmployer() { return
m_employer; }
double getWage() { return m_wage; }
};
// Teacher publicly inherits Person and
Employee
class Teacher: public Person, public
Employee
{
private:
int m_teachesGrade;
Problems with multiple inheritance
• While multiple inheritance seems like a simple extension
of single inheritance, multiple inheritance introduces a
lot of issues that can markedly increase the complexity
of programs and make them a maintenance nightmare.
Let’s take a look at some of these situations.
• First, ambiguity can result when multiple base classes contain a
function with the same name. For example:
Problems with multiple inheritance
Example
• long getID() { return m_id; }
• };
• class NetworkDevice
• {
• private:
• long m_id;
• public:
• NetworkDevice(long id)
• : m_id(id) {
• }
•
#include <iostream>
class USBDevice
{
private:
long m_id;
public:
USBDevice(long id)
: m_id(id)
{
}
Problems with multiple inheritance
Example
{
}
};
int main()
{
WirelessAdapter c54G(5442, 181742);
std::cout << c54G.getID(); // Which
getID() do we call?
return 0;
}
long getID() { return m_id; }
};
class WirelessAdapter: public
USBDevice, public
NetworkDevice
{
public:
WirelessAdapter(long usbId,
long networkId)
: USBDevice(usbId),
NetworkDevice(networkId)
Problems with multiple inheritance
Example
• When c54G.getID() is compiled, the compiler looks to see if
WirelessAdapter contains a function named getID(). It doesn’t.
The compiler then looks to see if any of the parent classes have a
function named getID(). See the problem here? The problem is
that c54G actually contains TWO getID() functions: one inherited
from USBDevice, and one inherited from NetworkDevice.
Consequently, this function call is ambiguous, and you will receive
a compiler error if you try to compile it.
Solution
• However, there is a way to work around this problem: you can
explicitly specify which version you meant to call:
int main()
{
WirelessAdapter c54G(5442, 181742);
std::cout << c54G.USBDevice::getID();
return 0;
}
Solution
• While this workaround is pretty simple, you can see how things
can get complex when your class inherits from four or six base
classes, which inherit from other classes themselves. The
potential for naming conflicts increases exponentially as you
inherit more classes, and each of these naming conflicts needs to
be resolved explicitly.
Diamond Problem
• Second, and more serious is the diamond problem, which your
author likes to call the “diamond of doom”. This occurs when a
class multiply inherits from two classes which each inherit from a
single base class. This leads to a diamond shaped inheritance
pattern.
Diamond Problem Example

More Related Content

What's hot

Applications Android - cours 11 : Boites de dialogue
Applications Android - cours 11 : Boites de dialogueApplications Android - cours 11 : Boites de dialogue
Applications Android - cours 11 : Boites de dialogueAhmed-Chawki Chaouche
 
Architecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependancesArchitecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependancesENSET, Université Hassan II Casablanca
 
Cours de programmation en c
Cours de programmation en cCours de programmation en c
Cours de programmation en cbenouini rachid
 
Spring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSpring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSyrine Ben aziza
 
C5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natC5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natPRONETIS
 
Correction Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdfCorrection Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdfslimyaich3
 
Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)Eric SIBER
 
UML Part 4- diagrammres de classes et d'objets mansouri
UML Part 4- diagrammres de classes et d'objets mansouriUML Part 4- diagrammres de classes et d'objets mansouri
UML Part 4- diagrammres de classes et d'objets mansouriMansouri Khalifa
 
POO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 EncapsulationPOO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 EncapsulationMouna Torjmen
 
Cours javascript
Cours javascriptCours javascript
Cours javascriptkrymo
 
Legacy code refactoring video rental system
Legacy code refactoring   video rental systemLegacy code refactoring   video rental system
Legacy code refactoring video rental systemJaehoon Oh
 
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅GDB와 strace로 Hang 걸린 Python Process 원격 디버깅
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅Youngmin Koo
 
Android - Tp1 - installation et démarrage
Android - Tp1 -   installation et démarrageAndroid - Tp1 -   installation et démarrage
Android - Tp1 - installation et démarrageLilia Sfaxi
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 

What's hot (20)

Applications Android - cours 11 : Boites de dialogue
Applications Android - cours 11 : Boites de dialogueApplications Android - cours 11 : Boites de dialogue
Applications Android - cours 11 : Boites de dialogue
 
Architecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependancesArchitecture jee principe de inversion de controle et injection des dependances
Architecture jee principe de inversion de controle et injection des dependances
 
spring-api-rest.pdf
spring-api-rest.pdfspring-api-rest.pdf
spring-api-rest.pdf
 
Cours de programmation en c
Cours de programmation en cCours de programmation en c
Cours de programmation en c
 
Spring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSpring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrine
 
Site JEE de ECommerce Basé sur Spring IOC MVC Security JPA Hibernate
Site JEE de ECommerce  Basé sur Spring IOC MVC Security JPA HibernateSite JEE de ECommerce  Basé sur Spring IOC MVC Security JPA Hibernate
Site JEE de ECommerce Basé sur Spring IOC MVC Security JPA Hibernate
 
C5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natC5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-nat
 
Sécurité des Applications Web avec Json Web Token (JWT)
Sécurité des Applications Web avec Json Web Token (JWT)Sécurité des Applications Web avec Json Web Token (JWT)
Sécurité des Applications Web avec Json Web Token (JWT)
 
Support programmation orientée objet c# .net version f8
Support programmation orientée objet c#  .net version f8Support programmation orientée objet c#  .net version f8
Support programmation orientée objet c# .net version f8
 
Cours design pattern m youssfi partie 7 facade bridge flyweight
Cours design pattern m youssfi partie 7 facade bridge flyweightCours design pattern m youssfi partie 7 facade bridge flyweight
Cours design pattern m youssfi partie 7 facade bridge flyweight
 
Correction Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdfCorrection Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdf
 
UML
UMLUML
UML
 
Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)
 
UML Part 4- diagrammres de classes et d'objets mansouri
UML Part 4- diagrammres de classes et d'objets mansouriUML Part 4- diagrammres de classes et d'objets mansouri
UML Part 4- diagrammres de classes et d'objets mansouri
 
POO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 EncapsulationPOO Java Chapitre 2 Encapsulation
POO Java Chapitre 2 Encapsulation
 
Cours javascript
Cours javascriptCours javascript
Cours javascript
 
Legacy code refactoring video rental system
Legacy code refactoring   video rental systemLegacy code refactoring   video rental system
Legacy code refactoring video rental system
 
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅GDB와 strace로 Hang 걸린 Python Process 원격 디버깅
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅
 
Android - Tp1 - installation et démarrage
Android - Tp1 -   installation et démarrageAndroid - Tp1 -   installation et démarrage
Android - Tp1 - installation et démarrage
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 

Similar to C++ Multiple Inheritance Guide

Similar to C++ Multiple Inheritance Guide (20)

Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
29c
29c29c
29c
 
29csharp
29csharp29csharp
29csharp
 
2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - Inheritance
 
Inheritance
Inheritance Inheritance
Inheritance
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
Inheritance
InheritanceInheritance
Inheritance
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdf
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introduction
 
Inheritance_abstractclass_interface.pdf
Inheritance_abstractclass_interface.pdfInheritance_abstractclass_interface.pdf
Inheritance_abstractclass_interface.pdf
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
C++primer
C++primerC++primer
C++primer
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 

More from zindadili

Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaingzindadili
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Polymorphism
PolymorphismPolymorphism
Polymorphismzindadili
 
Function overloading
Function overloadingFunction overloading
Function overloadingzindadili
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritancezindadili
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritancezindadili
 
Abstraction1
Abstraction1Abstraction1
Abstraction1zindadili
 
Access specifier
Access specifierAccess specifier
Access specifierzindadili
 
Friend function
Friend functionFriend function
Friend functionzindadili
 

More from zindadili (19)

Namespaces
NamespacesNamespaces
Namespaces
 
Namespace1
Namespace1Namespace1
Namespace1
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Templates2
Templates2Templates2
Templates2
 
Templates1
Templates1Templates1
Templates1
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Aggregation
AggregationAggregation
Aggregation
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritance
 
Abstraction1
Abstraction1Abstraction1
Abstraction1
 
Abstraction
AbstractionAbstraction
Abstraction
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Friend function
Friend functionFriend function
Friend function
 
Enum
EnumEnum
Enum
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 

C++ Multiple Inheritance Guide

  • 2. Multiple Inheritance • If a class is derived from two or more base classes then it is called multiple inheritance. In C++ multiple inheritance a derived class has more than one base class. • Multiple inheritance enables a derived class to inherit members from more than one parent.
  • 3. Difference in Multipe Inheritance & Multilevel Inheritance • Though but multiple and multilevel sounds like same but they differ hugely in meaning. In multilevel inheritance, we have multiple parent classes whereas in in multiple inheritance we have multiple base classes. • To put it in simple words, in multilevel inheritance, a class is derived from a class which is also derived from another base class. And these levels of inheritance can be extended. On the contrary, in multiple inheritance, a class is derived from two different base classes.
  • 4. For example • Multilevel inheritance : Inheritance of characters by a child from father and father inheriting characters from his father (grandfather) • Multiple inheritance : Inheritance of characters by a child from mother and father
  • 5. C++ Multiple Inheritance Block Diagram
  • 6. C++ Multiple Inheritance Syntax • class A • { • .......... • }; • class B • { • ........... • } ; • class C : acess_specifier A,access_specifier A // derived class from A and B • { • ........... • } ;
  • 7. C++ Multiple Inheritance Example #include using namespace std; class A {public: int x; void getx() { cout << "enter value of x: "; cin >> x; } }; class B { public: int y; void gety() { cout << "enter value of y: "; cin >> y; } };
  • 8. C++ Multiple Inheritance Example class C : public A, public B //C is derived from class A and class B { public: void sum() {cout << "Sum = " << x + y; } }; int main() { C obj1; //object of derived class C obj1.getx(); obj1.gety(); obj1.sum(); return 0; } //end of program
  • 9. C++ Multiple Inheritance Example Output enter value of x: 5 enter value of y: 4 Sum = 9
  • 10. C++ Multiple Inheritance Example 2 Let’s say we wanted to write a program to keep track of a bunch of teachers. A teacher is a person. However, a teacher is also an employee (they are their own employer if working for themselves). Multiple inheritance can be used to create a Teacher class that inherits properties from both Person and Employee. To use multiple inheritance, simply specify each base class (just like in single inheritance), separated by a comma.
  • 12. C++ Multiple Inheritance Example 2 • std::string getName() { return m_name; } • int getAge() { return m_age; } • }; • class Employee • { • private: • std::string m_employer; • double m_wage; • public: • Employee(std::string employer, double wage) • : m_employer(employer), m_wage(wage) • { • } #include <string> class Person { private: std::string m_name; int m_age; public: Person(std::string name, int age) : m_name(name), m_age(age) { }
  • 13. C++ Multiple Inheritance Example 2 public: Teacher(std::string name, int age, std::string employer, double wage, int teachesGrade) : Person(name, age), Employee(employer, wage), m_teachesGrade(teachesGrade) { } }; std::string getEmployer() { return m_employer; } double getWage() { return m_wage; } }; // Teacher publicly inherits Person and Employee class Teacher: public Person, public Employee { private: int m_teachesGrade;
  • 14. Problems with multiple inheritance • While multiple inheritance seems like a simple extension of single inheritance, multiple inheritance introduces a lot of issues that can markedly increase the complexity of programs and make them a maintenance nightmare. Let’s take a look at some of these situations. • First, ambiguity can result when multiple base classes contain a function with the same name. For example:
  • 15. Problems with multiple inheritance Example • long getID() { return m_id; } • }; • class NetworkDevice • { • private: • long m_id; • public: • NetworkDevice(long id) • : m_id(id) { • } • #include <iostream> class USBDevice { private: long m_id; public: USBDevice(long id) : m_id(id) { }
  • 16. Problems with multiple inheritance Example { } }; int main() { WirelessAdapter c54G(5442, 181742); std::cout << c54G.getID(); // Which getID() do we call? return 0; } long getID() { return m_id; } }; class WirelessAdapter: public USBDevice, public NetworkDevice { public: WirelessAdapter(long usbId, long networkId) : USBDevice(usbId), NetworkDevice(networkId)
  • 17. Problems with multiple inheritance Example • When c54G.getID() is compiled, the compiler looks to see if WirelessAdapter contains a function named getID(). It doesn’t. The compiler then looks to see if any of the parent classes have a function named getID(). See the problem here? The problem is that c54G actually contains TWO getID() functions: one inherited from USBDevice, and one inherited from NetworkDevice. Consequently, this function call is ambiguous, and you will receive a compiler error if you try to compile it.
  • 18. Solution • However, there is a way to work around this problem: you can explicitly specify which version you meant to call: int main() { WirelessAdapter c54G(5442, 181742); std::cout << c54G.USBDevice::getID(); return 0; }
  • 19. Solution • While this workaround is pretty simple, you can see how things can get complex when your class inherits from four or six base classes, which inherit from other classes themselves. The potential for naming conflicts increases exponentially as you inherit more classes, and each of these naming conflicts needs to be resolved explicitly.
  • 20. Diamond Problem • Second, and more serious is the diamond problem, which your author likes to call the “diamond of doom”. This occurs when a class multiply inherits from two classes which each inherit from a single base class. This leads to a diamond shaped inheritance pattern.